Wednesday, February 22, 2017

Java’s Synchronized Keyword in Three Minutes

The synchronized keyword can be used to ensure that only one thread at a time executes a particular section of code. This is a simple way to prevent race conditions, which occur when several threads change shared data at the same time in a way that leads to incorrect results. With synchronized either entire methods or selected blocks can be single-threaded.

This article requires basic knowledge of Java threads and race conditions.

Synchronization Basics

Let's see how to use synchronized on methods and, more fine-grained, on code blocks. I will also explain how it works.

Using The synchronized Keyword

If we add a synchronized modifier to a method, the JVM guarantees that only one thread can execute a method at the same time:

class MutableInteger {

    private int value;

    public synchronized void increment() {
        value++;
    }

    public synchronized int getValue() {
        return value;
    }

}

If several threads try to execute a synchronized method simultaneously, only one will be able to do it. The others will be paused until the first one exits the method. (In some sense it works much like a traffic light, making sure concurrent executions don't collide.) Because of this, threads that increment the value counter do not overwrite each other's results and every increment will be recorded.

To see that the synchronized keyword works I create ten threads that each increment the same counter ten thousand times. I created a gist with the code - it is basically the same as in the article explaining race conditions. As expected, the result is always the same and always correct:

Result value: 100000

The synchronized keyword only limits thread access to one object. If you have two different instances, two different threads can use them at the same time, and they won't block each other:

MutableInteger integer1 = new MutableInteger();
MutableInteger integer2 = new MutableInteger();
// Threads are using different objects and don't
// interact with each other
Thread thread1 = new Thread(new IncrementingRunnable(integer1));
Thread thread2 = new Thread(new IncrementingRunnable(integer2));

How synchronized Works

Continue reading %Java’s Synchronized Keyword in Three Minutes%


by Ivan Mushketyk via SitePoint

No comments:

Post a Comment