Synchronized
This lesson explains the all-important synchronized keyword.
We'll cover the following...
Question # 1
What is synchronized?
Java’s most fundamental construct for thread synchronization is the synchronized
keyword. It can be used to restrict access to critical sections one thread at a time.
Each object in Java has an entity associated with it called the monitor lock or just monitor. Think of it as an exclusive lock. Once a thread gets hold of the monitor of an object, it has exclusive access to all the methods marked as synchronized
. No other thread will be allowed to invoke a method on the object that is marked as synchronized
and will block, till the first thread releases the monitor which is equivalent of the first thread exiting the synchronized
method.
Note carefully:
For static methods, the monitor will be the class object, which is distinct from the monitor of each instance of the same class.
If an uncaught exception occurs in a synchronized method, the monitor is still released.
Furthermore, synchronized blocks can be re-entered that is they are ...