Search code examples
javaconcurrencyjava.util.concurrentlocks

Reenterant Lock Object Locking


I am trying to make certain objects synchronized and the code looks like below:

    conLock.tryLock();
        this.end();
        Obj1 = Obj2;
        Obj3 = Obj4.build();
    } finally {

        conLock.unlock();
    }

Can some one please help whether all the Objects will be locked for modification till the time the lock is unlocked.

Any section of the documentation will also be helpful.


Solution

  • all the Objects will be locked for modification

    Locks in Java (neither via synchronized keyword or via Lock implementations) do not protect anything directly. Nothing gets "locked for modification" as such.

    They are merely "advisory" locks, a protocol that allows you to write thread-safe code by making sure your code coordinates execution properly with these locks. But it remains up to you to make sure that all "critical sections" (such as the code paths where you modify some mutable state) are appropriately covered (i.e. take out the locks you need to take out).

    They do not prevent you from writing (or executing) code that ignores the locks.