Synchronization
Home ] Up ] A Steam Boiler ] Race Conditions ] Monitors ] [ Synchronization ] A Fixed Steam Boiler ] Deadlock ] Starvation & Livelock ]

 

 

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:

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. As a convenience, a method may be declared synchronized; such a method behaves as if its body were contained in a synchronized statement.

(The Java Virtual Machine Specification, by Tim Lindholm & Frank Yellin, published by Addison Wesley, 1997, page 53.)

Here are some examples of the use of synchronized keyword:

package threads;

public class SharedResource
{
    // ...

    private String m_value = "";

    public synchronized void setValue(String value)  // 1
    {
        m_value = value;
    }

    public synchronized String getValue()	            // 2
    {
        return m_value;
    }

    private static int m_count = 0;

    public static synchronized void incrementCount() // 3
    {
        m_count++;
    }

    private Double m_salary = new Double(32000.0);

    public void giveRaise(double percent)
    {
        synchronized (m_salary) 		            // 4
        {
            double salary = m_salary.doubleValue();
            salary += salary * percent /100;
            m_salary = new Double(salary);
        }
    }
}

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: The synchronization may not be on an instance of a primitive type, such as 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