Tuesday, 17 November 2015

What is synchronization ? Difference b/w synchronized method & block

Synchronization: To prevent multiple threads accessing on same object (or) Only one thread at a time can access synchronized methods or blocks. synchronized keyword can be applied to static/non-static methods or a block of code. Synchronization can handle in 2 ways either synchronized block or synchronized method
 
S.No
Synchronized Block
Synchronized Method
1
Scope of lock is low so performance is high
Scope of lock is high so performance is low
2
It can throw java.lang.NullPointerException if expression provided to block as parameter evaluates to null
It is not the case with synchronized methods
3
In this, thread acquires lock when they enter synchronized block and release when they leave synchronized block
In this, lock is acquired by thread when it enter method and released when it leaves method, either normally or by throwing Exception
4
It is better Java coding practices compared to synchronized() method
It is not better Java coding practices compared to synchronized block
Note: Depends on situation, We need to use synchronized method and synchronized block.

Synchronized method example:

Synchronized block example:

No comments:

Post a Comment