Monday 1 May 2017

Key Points about synchronized keyword in java

What is Synchronized keyword?
Synchronized keyword is used to provide mutual exclusive access of a shared resource with multiple threads.

Synchronization guarantees that, no two threads can execute a synchronized method which requires same lock simultaneously or concurrently.

How it works?
Whenever a thread enters into synchronized method or block it acquires a lock and whenever it leaves synchronized method or block it releases the lock.

Lock is released even if thread leaves synchronized method after completion or due to any Error or Exception.

Object or Class level locking?
Thread acquires an object level lock when it enters into an instance synchronized method and acquires a class level lock when it enters into static synchronized method.

synchronized keyword is re-entrant in nature
It means if a synchronized method calls another synchronized method which requires same lock then current thread which is holding lock can enter into that method without acquiring lock.

NullPointerException
synchronization will throw NullPointerException if object used synchronized block is null.synchronized(instance) will throws java.lang.NullPointerException if instance is null.

synchronized block is better than synchronized method
synchronized block is better than synchronized method in Java because by using synchronized block, it lock only critical section of code and avoid locking whole method which can possibly degrade performance.

It’s possible that both static synchronized and non-static synchronized method can run simultaneously or concurrently because they lock on different object.

volatile keyword usage – To avoid the memory consistency error
From java 5 after change in Java memory model reads and writes are atomic for all variables declared using volatile keyword (including long and double variables) and simple atomic variable access is more efficient instead of accessing these variables via synchronized java code. But it requires more care and attention from the programmer to avoid memory consistency errors.

synchronized keyword with constructor
According to the Java language specification we cannot use Java synchronized keyword with constructor it’s illegal and result in compilation error. So you cannot synchronized constructor which seems logical because other threads cannot see the object being created until the thread creating it has finished it.

Reentrant lock
Java.util.concurrent.locks extends capability provided by synchronized keyword for writing more sophisticated programs since they offer more capabilities e.g. Reentrancy and interruptible locks.

synchronized keyword also synchronizes memory.
In fact synchronized synchronizes the whole of thread memory with main memory.

Important method related to synchronization in are wait (), notify() and notifyAll() which is defined in Object class always call in synchronized block or method.

Do not synchronize non-final field on synchronized block
Because reference of non-final field may change any time and then different thread might synchronizing on different objects i.e. no synchronization at all.


private String lock = new String("lock"); // non-final.
synchronized(lock){
    System.out.println("locking on :"  + lock);
}

synchronized code may get warning "Synchronization on non-final field"  in IDE like Netbeans and InteliJ.

Do not String object as lock in java synchronized block
It is not recommended to use String object as lock in java synchronized block because string is immutable object and literal string and interned string gets stored in String pool.

So by any chance if any other part of code or any third party library used same String as there lock then they both will be locked on same object despite being completely unrelated which could result in unexpected behavior and bad performance.
Instead of String object it’s advised to use new Object () for Synchronization in Java on synchronized block.


private static final String LOCK = "lock";   //not recommended
private static final Object OBJ_LOCK = new Object(); //better
public void process() {
   synchronized(LOCK) {
    ........
   }
}

Calendar and SimpleDateFormat
From Java library Calendar and SimpleDateFormat classes are not thread-safe , requires external synchronization in Java to be used in multi-threaded environment.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...