|
|
|
|
In Java, every object has an associated monitor which may be used to serialize access to that object. Also, every class has an associated monitor to serialize access to the class. The Java Virtual Machine implements the necessary support for these monitors. The Java language adds a construct to allow a programmer to specify when a monitor is to be used -- the synchronized keyword:
Here are some examples of the use of synchronized keyword:
Methods 1 and 2, because they are instance methods, synchronize on the object's (or instance's) monitor. Method 3, because it is a class (static) method, synchronizes on the class' monitor. The synchronized statement at 4 specifies that it synchronizes on m_salary, an instance of class Double.
Note that methods getValue(), incrementCount() and raiseSalary() may all be executing concurrently in different threads, because they synchronize on different monitors. A thread may call a synchronized method on an object for which it already holds the lock. This is called reacquiring the lock, and is allowed because Java monitors are reentrant. Because of this, a single thread cannot deadlock itself on a lock it already holds.
|
| The page was last updated February 19, 2008 |