Lock in Java Programming

Lock in Java Programming

Previous Home Next

 

To synchronize threads, the Java programming language uses monitors, which are a high-level mechanism for allowing only one thread at a time to of code execute a region  protected by the monitor.  The behavior of monitors is explained in terms of locks; there is a lock associated with each object.

The synchronized statement performs two special actions relevant only to multithreaded operation.

1) after computing a reference to an object but before executing its body, it locks a lock associated with the object.

(2) after execution of the body has completed, either normally or abruptly, it unlocks that same lock.
 

All Lock implementations must enforce the same memory synchronization semantics as provided by the built-in monitor lock:

     A successful lock operation acts like a successful monitorEnter action
     A successful unlock operation acts like a successful monitorExit action




 

Lock l = ...;
l.lock();
try {
// access the resource protected by this lock
} finally {
l.unlock();
}


Previous Home Next