Multithreading - Synchronization

When multiple threads need to access a shared resource, they need to ensure that, at a time, only single thread accesses the resource. The process by which this is achieved is called synchronization.

Also, when multiple threads operate on the same object, that can lead to data corruption. This is also known as race condition. To prevent this, we need to use synchronization.

Every object has a monitor that is a mutually exclusive lock for that object. When a thread owns the lock, it basically enters the monitor. All other threads will have to wait until the first thread exits the monitor.

Java provides with synchronized keyword. It is applicable to methods and code blocks but not on classes and variables.

Whenever a thread needs to acquire lock of an object, it simply calls the synchronized method of the object. To release the lock, it returns from the method or the code block.

public synchronized void synchronizedPrinter(String name) {
    for(int i=0;i<250;i++) {
        System.out.println(name + " " + i);    }
}

The above method can be executed by one method at a time.
Also, if a thread has to execute synchronized methods of different objects, it will acquire locks of all those objects.

An example showing sychronized and non-synchronized behaviour can be found here

If a static method is synchronized, then a class-level lock is acquired by the thread.

Similarly, synchronized  can also be applied to code blocks.
They are applicable to :
1. synchronized(this) - current object lock
2. synchronized(obj) - get lock of Object obj
3. synchronized(ClassName.class) - get lock of class

Comments

Popular posts from this blog

Collection Framework - HashSet And LinkedHashSet class

Collection Framework - Cursors in Java

Hashed data structures