Synchronized Statement in Java

time to read 1 min | 118 words

synchronized statements can be used to avoid memory inconsistency errors and thread interference in multi-threaded programs.

When a thread executes code within a synchronized statement, the object passed as a parameter is locked. When writing a synchronized block, the object providing the lock must be specified after the synchronized keyword:

public class Rezha {
  private int sum;
  public void addToSum(int value) {
    synchronized(this) {
      sum += value;   
    }
  }
}

In this example the object providing the lock is this, which is the instance of Rezha that the method is being called in.

You can lock instances of other classes as well:

public class Rezha {
  private MyObject mo;

  public void myMethod(){
    synchronized(mo){
      //code here
    }
  }
}