Synchronization in Java with Examples

Synchronization of threads is needed for in order to control threads coordination, mainly in order to prevent simultaneous operations on data.

A shared resource may be corrupted if it is accessed simultaneously by multiple threads. For example, two unsynchronized threads accessing the same bank account may cause conflict.

For simple synchronization Java provides the synchronized keyword. For more sophisticated locking mechanisms, starting from Java 5, the package java.concurrent.locks provides additional locking options.

Synchronizing instance methods and static methods: 

A synchronized method acquires a lock before it executes. In the case of an instance method, the lock is on the object for which the method was invoked. In the case of a static method, the lock is on the class. If one thread invokes a synchronized instance method (respectively, static method) on an object, the lock of that object (respectively, class) is acquired first, then the method is executed, and finally the lock is released. Another thread invoking the same method of that object (respectively, class) is blocked until the lock is released.

public class SynchronizedCounter {
    private int c = 0;

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

    public synchronized void decrement() {
        c--;
    }

    public synchronized int value() {
        return c;
    }
}

Synchronizing blocks: 

A synchronized statement can be used to acquire a lock on any object, not just this object, when executing a block of the code in a method. This block is referred to as a synchronized block.

public void addName(String name) {
  synchronized (this) {
    lastName = name;
    nameCount++;
    }
    nameList.add(name);
}


When synchronizing a block, key for the locking should be supplied (usually would be this) The advantage of not synchronizing the entire method is efficiency.

Search:

Recent Posts