Synchronize Keyword

Synchronize keyword is one of the most common and basic concept used for thread concurrency in java. There are applications running in multithreaded environment where multiple threads can access/modify the same object. In most of the use case this is not desirable behavior since update by one thread may not be visible to other thread at the same point of time. Synchronized keyword can be applied to static/non-static methods or a block of code. Only one thread at a time can access synchronized block and if there are multiple threads trying to access the same method then other threads have to wait for the execution of method by one thread. The block of code which is wrapped by a synchronized keyword can be called as criticla section.

When a thread wants to enter the critical section, it has to acquire the lock. Only one thread can acquire a lock at a given point of time. Once the thred is finished with critical section it releases the lock and other threads can acquire it.

The synchronized keywrod can be applied to:

Synchronized methods

Here is simple example:


  int totalCount = 0;
  public int synchronize visits() {
    totalCount++;
    return totalCount;
  }

In above code, only one thread can enter the visits() method at a give point of time and will increment the totalCount value. When a thread acquires a enters the sychronized method of a object, internally it acquires a lock on a monitor and it has the right to enter any other synchronized method of the same class.

Synchronized Static methods

Here is simple example:


  static int totalCount = 0;
  public static int synchronize visits() {
    totalCount++;
    return totalCount;
  }

These methods are synchronized on the Class object associated with the class and since only one Class object exists per JVM per class, only one thread can execute inside a static synchronized method per class, irrespective of the number of instances it has.

Synchronized blocks

It is always not necessary to acquire lock on the entire method. In such a case lock can be acquired on a block. The block can be present in a static or instance methods.


  int totalCount = 0;
  public  int synchronize visits() {
  	syhcronized(this) {
  		totalCount++;
  }
    
    return totalCount;
}
public Class TestC {
  static int totalCount = 0;
  public static int synchronize visits() {
  	syhcronized(TestC.class) {
  		totalCount++;
    }
    return totalCount;
  }
}

I guess one could see the difference between two blocks. To acquire a lock on instance method this keyword is used. This is the monitor object, the code inside the block get synchronized on the monitor object. But in case the method is static, we would pass class name in place of the object reference. And the class would be a monitor for synchronization of the block.

Understanding Concurrency and multi-threading environment is important to a large scale applications. Have synchronized keyword can make the application slow because threads have to wait to enter the critical section so one have to find the right code block to make in thread safe.

As an alternative to a synchronized block you could also use one of the many atomic data types found in the java.util.concurrent package. For instance, the AtomicLong or <AtomicReference or one of the others.


Recommend Reading

  1. How java manages Memory?
  2. Why is it advised to use hashcode and equals together?
  3. Comparable and Comparator in java
  4. How to create Singleton class in Java?
  5. Difference between equals and ==?
  6. When to use abstract class over interface?
  7. Difference between final, finally and finalize
  8. Why is it recommended to use Immutable objects in Java