If you’re working with Spring, check out "REST With Spring":

>> CHECK OUT THE COURSE

1. Overview

This quick article will be an intro to using the synchronized block in Java.

Simply put, in a multi-threaded environment, a race condition occurs when two or more threads attempt to update mutable shared data at the same time. Java offers a mechanism to avoid race conditions by synchronizing thread access to shared data. 

A piece of logic marked with synchronized becomes a synchronized block, allowing only one thread to execute at any given time.

2. Why Synchronization?

Let’s a consider a typical race condition where we calculate the sum and multiple threads execute the calculate()  method:

public class BaeldungSynchronizedMethods {

    private int sum = 0;

    public void calculate() {
        setSum(getSum() + 1);
    }

    // standard setters and getters
}

And let’s write a simple test:

@Test
public void givenMultiThread_whenNonSyncMethod() {
    ExecutorService service = Executors.newFixedThreadPool(3);
    BaeldungSynchronizedMethods summation = new BaeldungSynchronizedMethods();

    IntStream.range(0, 1000)
      .forEach(count -> service.submit(summation::calculate));
    service.awaitTermination(1000, TimeUnit.MILLISECONDS);

    assertEquals(1000, summation.getSum());
}

We’re simply using an ExecutorService with a 3-threads pool to execute the calculate() 1000 times.

If we would execute this serially, the expected output would be 1000, but our multi-threaded execution fails almost every time with an inconsistent actual output e.g.:

java.lang.AssertionError: expected:<1000> but was:<965>
at org.junit.Assert.fail(Assert.java:88)
at org.junit.Assert.failNotEquals(Assert.java:834)
...

This result is of course not unexpected.

A simple way to avoid the race condition is to make the operation thread-safe by using the synchronized keyword.

3. The synchronized Keyword

The synchronized keyword can be used on different levels:

  • Instance methods
  • Static methods
  • Code blocks

When we use a synchronized block, internally Java uses a monitor also known as monitor lock or intrinsic lock, to provide synchronization. These monitors are bound to an object, thus all synchronized blocks of the same object can have only one thread executing them at the same time.

3.1. Synchronized Instance Methods

Simply add the synchronized keyword in the method declaration to make the method synchronized:

public synchronized void synchronisedCalculate() {
    setSum(getSum() + 1);
}

Notice that once we synchronize the method, the test case passes, with actual output as 1000:

@Test
public void givenMultiThread_whenMethodSync() {
    ExecutorService service = Executors.newFixedThreadPool(3);
    SynchronizedMethods method = new SynchronizedMethods();

    IntStream.range(0, 1000)
      .forEach(count -> service.submit(method::synchronisedCalculate));
    service.awaitTermination(1000, TimeUnit.MILLISECONDS);

    assertEquals(1000, method.getSum());
}

Instance methods are synchronized over the instance of the class owning the method. Which means only one thread per instance of the class can execute this method.

3.2. Synchronized Static Methods

Static methods are synchronized just like instance methods:

 public static synchronized void syncStaticCalculate() {
     staticSum = staticSum + 1;
 }

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.

Let’s test it:

@Test
public void givenMultiThread_whenStaticSyncMethod() {
    ExecutorService service = Executors.newCachedThreadPool();

    IntStream.range(0, 1000)
      .forEach(count -> 
        service.submit(BaeldungSynchronizedMethods::syncStaticCalculate));
    service.awaitTermination(100, TimeUnit.MILLISECONDS);

    assertEquals(1000, BaeldungSynchronizedMethods.staticSum);
}

3.3. Synchronized Blocks within Methods

Sometimes we do not want to synchronize the entire method but only some instructions within it. This can be achieved by applying synchronized to a block:

public void performSynchrinisedTask() {
    synchronized (this) {
        setCount(getCount()+1);
    }
}

let us test the change:

@Test
public void givenMultiThread_whenBlockSync() {
    ExecutorService service = Executors.newFixedThreadPool(3);
    BaeldungSynchronizedBlocks synchronizedBlocks = new BaeldungSynchronizedBlocks();

    IntStream.range(0, 1000)
      .forEach(count -> 
        service.submit(synchronizedBlocks::performSynchronisedTask));
    service.awaitTermination(100, TimeUnit.MILLISECONDS);

    assertEquals(1000, synchronizedBlocks.getCount());
}

Notice, that we passed a parameter this to the synchronized block. This is the monitor object, the code inside the block get synchronized on the monitor object. Simply put, only one thread per monitor object can execute inside that block of code.

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:

public static void performStaticSyncTask(){
    synchronized (SynchronisedBlocks.class) {
        setStaticCount(getStaticCount() + 1);
    }
}

Let’s test the block inside the static method:

@Test
public void givenMultiThread_whenStaticSyncBlock() {
    ExecutorService service = Executors.newCachedThreadPool();

    IntStream.range(0, 1000)
      .forEach(count -> 
        service.submit(BaeldungSynchronizedBlocks::performStaticSyncTask));
    service.awaitTermination(100, TimeUnit.MILLISECONDS);

    assertEquals(1000, BaeldungSynchronizedBlocks.getStaticCount());
}

5. Conclusion

In this quick article, we have seen different ways of using the synchronized keyword to achieve thread synchronization.

We also explored how a race condition can impact our application, and how synchronization helps us avoid that. For more about thread safety using locks in Java refer to our java.util.concurrent.Locks article.

The complete code for this tutorial is available over on GitHub.

The new Certification Class of "REST With Spring" is finally out:

>> CHECK OUT THE COURSE

Sort by:   newest | oldest | most voted
Philippe
Guest

I’m trying to understand why it’s not working with a max range of 100000? Synchronized method test works every time with a max of 1000 or even 10000, but not with 100000 or even 20000 (sometimes). Am I doing something wrong or not understanding something?

java.lang.AssertionError:
Expected :20000
Actual :16582

EDIT : Running with a Sync Block `synchronized (this)` and `service.awaitTermination(…)` seems to work everytime but not with the synchronized method

Grzegorz Piwowarek
Guest

Which method are you running?

Standa
Guest

Do you call
service.shutdown()
service.awaitTermination(…)
?

Philippe
Guest

service.shutdown() yes

I’m assuming service.shutdown() is the problem here with the first example?

Using service.awaitTermination(…) with variables timeouts works the bigger the number. I guess that’s kind of logic since, say, 1 million iterations will take longer that 1000.

So yes I’m good now. Finally understanding how everything works.
Thanks for pointing me in a different direction 🙂

Thought
Guest

line 4 in the Junit will cause compiler error

Grzegorz Piwowarek
Guest

Which sample exactly? The snippets on GitHub are building fine so it might be a copy-paste failure.

Thought
Guest

And let’s write a simple test:

very first test
SynchronizedMethods summation = new SynchronizedMethods();
and class name is which is being tested is BaeldungSynchronizedMethods

Grzegorz Piwowarek
Guest

Thanks! Fixed.

wpDiscuz