Synchronized blocks in Java are marked with the synchronized keyword. All synchronized blocks synchronized on the same object can only have one thread executing inside them at the same time. All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block. The synchronized keyword can be used to mark four different types of blocks:

  1. Instance methods
  2. Static methods
  3. Code blocks inside instance methods
  4. Code blocks inside static methods

 

 

Synchronized Instance Methods

A synchronized instance method is synchronized on the instance (object) owning the method. Thus, each instance has its synchronized methods synchronized on a different object: the owning instance. Only one thread can execute inside a synchronized instance method. If more than one instance exist, then one thread at a time can execute inside a synchronized instance method per instance. One thread per instance.

public synchronized void add (int value){    
  this.count += value; 
}

 

Synchronized Static Methods
Static methods are marked as synchronized just like instance methods using the synchronized keyword. Synchronized static methods are synchronized on the class object of the class the synchronized static method belongs to. Since only one class object exists in the JVM per class, only one thread can execute inside a static synchronized method in the same class.

public static synchronized void add(int value){   
  count += value; 
}

 

Synchronized Blocks in Instance Methods
Sometimes it is preferable to synchronize only part of a method. Java synchronized blocks inside methods makes this possible.

public void add (int value){    
  synchronized(this){        
    this.count += value;     
  }
}

 

In the example “this” is used, which is the instance the add method is called on. The object taken in the parentheses by the synchronized construct is called a monitor object. The code is said to be synchronized on the monitor object. A synchronized instance method uses the object it belongs to as monitor object. Only one thread can execute inside a Java code block synchronized on the same monitor object.