Friday 16 October 2015

Synchronization


Synchronization in Java?

Synchronization in java is the capability to control the access of multiple threads to any shared resource.

Java Synchronization is better option where we want to allow only one thread to access the shared resource.

Why use Synchronization?

The synchronization is mainly used to

To prevent thread interference.
To prevent consistency problem.

Types of Synchronization

There are two types of synchronization

Process Synchronization
Thread Synchronization



Synchronized block in java

Synchronized block can be used to perform synchronization on any specific resource of the method.

main point :

Synchronized block is used to lock an object for any shared resource.
Scope of synchronized block is smaller than the method.

Synchronized method

Synchronized method is used to lock an object for any shared resource.

Difference between synchronized method vs block in Java

1.One significant difference between synchronized method and block is that, Synchronized block generally reduce scope of lock. As scope of lock is inversely proportional to performance, its always better to lock only critical section of code.

2.Synchronized block provide control over lock, as you can use arbitrary lock to provide mutual exclusion to critical section code. On the other hand synchronized method always lock either on current object represented by this keyword  or class level lock, if its static synchronized method.

3. Synchronized block can throw throw java.lang.NullPointerException.

4. In case of synchronized method, lock is acquired by thread when it enter method and released when they leaving method, either normally or by throwing Exception.
On the other hand in case of synchronized block, thread acquires lock when they enter synchronized block and release when they leave synchronized block.

The difference is in which lock is being acquired:

synchronized method acquires a method on the whole object. This means no other thread can use any synchronized method in the whole object while the method is being run by one thread.

synchronized blocks acquires a lock in the object between parentheses after the synchronized keyword. Meaning no other thread can acquire a lock on the locked object until the synchronized block exits.

So if you want to lock the whole object, use a synchronized method. If you want to keep other parts of the object accessible to other threads, use synchronized block.

If you choose the locked object carefully, synchronized blocks will lead to less contention, because the whole object/class is not blocked.

This applies similarly to static methods: a synchronized static method will acquire a lock in the whole class object, while a synchronized block inside a static method will acquire a lock in the object between parentheses.




No comments:

Post a Comment