Java Programming/Keywords/synchronized

From Wikibooks, open books for an open world
Jump to: navigation, 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:

  • Create a synchronized block
  • Mark a method synchronized

A synchronized block is marked as:

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

The syntax to mark a method synchronized is:

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

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]

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

Computer code Code listing 1: Singleton.java
  1. /**
    
  2.  * The singleton class that can be instantiated only once with lazy instantiation
    
  3.  */
    
  4. public class Singleton {
    
  5.     /** Static class instance */
    
  6.     private volatile static Singleton instance = null;
    
  7.  
    
  8.     /**
    
  9.      * Standard private constructor
    
  10.      */
    
  11.     private Singleton() {
    
  12.         // Some initialisation
    
  13.     }
    
  14.  
    
  15.     /**
    
  16.      * Getter of the singleton instance
    
  17.      * @return The only instance
    
  18.      */
    
  19.     public static Singleton getInstance() {
    
  20.         if (instance == null) {
    
  21.             // If the instance does not exist, go in time-consuming
    
  22.             // section:
    
  23.             synchronized (Singleton.class) {
    
  24.                 if (instance == null) {
    
  25.                     instance = new Singleton();
    
  26.                 }
    
  27.             }
    
  28.         }
    
  29.  
    
  30.         return instance;
    
  31.     }
    
  32.  }