Synchronization in Java
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
1.To prevent thread interference.
2.To prevent Consistency problem
Types of Synchronization
• There are two types of synchronization
1.Process Synchronization
2.Thread Synchronization
• Here, we will discuss only thread synchronization.
Thread Synchronization
• There are two types of thread synchronization mutual
exclusive and inter-thread communication.
1.Mutual Exclusive
1.Synchronized method.
2.Synchronized block.
3.Static synchronization.
2.Cooperation (Inter-thread communication in java)
Mutual Exclusive
• Mutual Exclusive helps keep threads from interfering with one another
while sharing data.
• It can be achieved by using the following three ways:
1. By Using Synchronized Method
2. By Using Synchronized Block
3. By Using Static Synchronization
Concept of Lock in Java
• Synchronization is built around an internal entity known as the lock or
monitor.
• Every object has a lock associated with it. By convention, a thread that
needs consistent access to an object's fields has to acquire the object's
lock before accessing them, and then release the lock when it's done
with them.
• From Java 5 the package java.util.concurrent.locks contains several lock
implementations.
(i)Synchronized Method
• If you declare any method as synchronized, it is known as
synchronized method.
• Synchronized method is used to lock an object for any shared
resource.
• When a thread invokes a synchronized method, it automatically
acquires the lock for that object and releases it when the thread
completes its task.
Synchronized Block in Java:
• Synchronized block can be used to perform synchronization on any
specific resource of the method.
• Suppose we have 50 lines of code in our method, but we want to
synchronize only 5 lines, in such cases, we can use synchronized block.
• If we put all the codes of the method in the synchronized block, it will
work same as the synchronized method.
Continuee..(Points to Remember)
• Synchronized block is used to lock an object for any shared resource.
• Scope of synchronized block is smaller than the method.
• A Java synchronized block doesn't allow more than one JVM, to
provide access control to a shared resource.
• The system performance may degrade because of the slower working
of synchronized keyword.
• Java synchronized block is more efficient than Java synchronized
method.
Syntax
• synchronized (object reference expression) {
• //code block
•}