Java Programming/Keywords/synchronized

From Wikibooks, open books for an open world
Jump to navigation Jump to search

synchronized is a keyword.

It marks a critical section. A critical section is where one and only one thread is executing. So to enter into the marked code the threads are synchronized, only one can enter, the others have to wait. For more information see Synchronizing Threads Methods or [1].

The synchronized keyword can be used in two ways:

A synchronized block is marked as:

Example Code section 1: Synchronized block.
synchronized(<object_reference>) {
   // Thread.currentThread() has a lock on object_reference. All other threads trying to access it will
   // be blocked until the current thread releases the lock.
}

The syntax to mark a method synchronized is:

Example Code section 2: Synchronized method.
public synchronized void method() {
   // Thread.currentThread() has a lock on this object, i.e. a synchronized method is the same as
   // calling { synchronized(this) {…} }.
}

The synchronization is always associated to an object. If the method is static, the associated object is the class. If the method is non-static, the associated object is the instance. While it is allowed to declare an abstract method as synchronized, it is meaningless to do so since synchronization is an aspect of the implementation, not the declaration, and abstract methods do not have an implementation.

Singleton example[edit | edit source]

As an example, we can show a thread-safe version of a singleton:

Computer code Code listing 1: Singleton.java
/**
 * The singleton class that can be instantiated only once with lazy instantiation
 */
public class Singleton {
    /** Static class instance */
    private volatile static Singleton instance = null;

    /**
     * Standard private constructor
     */
    private Singleton() {
        // Some initialisation
    }
   
    /**
     * Getter of the singleton instance
     * @return The only instance
     */
    public static Singleton getInstance() {
        if (instance == null) {
            // If the instance does not exist, go in time-consuming
            // section:
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }

        return instance;
    }
 }