In Java, the threads are executed independently to each other. These types of threads are called as asynchronous threads.
Synchronized Threads
In Java, the threads are executed independently to each other. These types of threads are called as asynchronous threads. But there are two problems may be occur with asynchronous threads.
- Two
or more threads share the same resource (variable or method) while only one
of them can access the resource at one time.
- If the producer and the consumer are sharing the same kind of data in a program then either producer may produce the data faster or consumer may retrieve an order of data and process it without its existing.
Suppose, we have created two methods as increment( ) and decrement( ). which increases or decreases value of the variable "count" by 1 respectively shown as:
public void increment( ) { count++; } public void decrement( ) { count--; } public int value() { return count; } |
When the two threads are executed to access these
methods (one for increment( ),another for
decrement( )) then both will share the
variable "count". in that case, we can't be sure that what
value will be returned of variable "count".
We can see this problem in the diagram
shown below:
To avoid this problem, Java uses monitor also known as ?semaphore? to prevent data from being corrupted by multiple threads by a keyword synchronized to synchronize them and intercommunicate to each other. It is basically a mechanism which allows two or more threads to share all the available resources in a sequential manner. Java's synchronized is used to ensure that only one thread is in a critical region. critical region is a lock area where only one thread is run (or lock) at a time. Once the thread is in its critical section, no other thread can enter to that critical region. In that case, another thread will has to wait until the current thread leaves its critical section.
General form of the synchronized statement is as:
synchronized(object) { // statements to be synchronized } |
Lock:
Lock term refers to the access granted to
a particular thread that can access the shared resources. At any given time,
only one thread can hold the lock and thereby have access to the shared
resource. Every object in Java has build-in lock that only comes in action when
the object has synchronized method code. By associating a shared resource with a
Java object and its lock, the object can act as a guard, ensuring synchronized
access to the resource. Only one thread at a time can access the shared resource
guarded by the object lock.
Since there is one lock per object, if one thread has acquired the lock, no
other thread can acquire the lock until the lock is not released by first
thread. Acquire the lock means the thread currently in synchronized method and
released the lock means exits the synchronized method. Remember the following
points related to lock and synchronization:
- Only methods (or blocks) can be synchronized, Classes and variable cannot
be.
- Each object has just one lock.
- All methods in a class need not to be synchronized. A class can have both
synchronized and non-synchronized methods.
- If two threads wants to execute a synchronized method in a class, and both
threads are using the same instance of the class to invoke the method then
only one thread can execute the method at a time.
- If a class has both synchronized and non-synchronized methods, multiple
threads can still access the class's non-synchronized methods. If you have
methods that don't access the data you're trying to protect, then you don't
need to synchronize them. Synchronization can cause a hit in some cases (or
even deadlock if used incorrectly), so you should be careful not to overuse
it.
- If a thread goes to sleep, it holds any locks it has?it doesn't release
them.
- A thread can acquire more than one lock. For example, a thread can enter a
synchronized method, thus acquiring a lock, and then immediately invoke a
synchronized method on a different object, thus acquiring that lock as well.
As the stack unwinds, locks are released again.
- You can synchronize a block of code rather than a method.
- Constructors cannot be synchronized
There are two ways to synchronized the execution of code:
- Synchronized Methods
- Synchronized Blocks (Statements)
Synchronized Methods:
Any method is
specified with the keyword synchronized is only
executed by one thread at a time. If any thread want to execute the synchronized
method, firstly it has to obtain the objects lock. If the lock is already held by another thread, then
calling thread has to wait.
Synchronized methods are useful in those situations where methods are executed
concurrently, so that these can be intercommunicate manipulate
the state of an object in ways that can corrupt the state if . Stack implementations usually define the two operations push and
pop of elements as synchronized, that?s why pushing and popping are mutually
exclusive operations. For Example if several threads were sharing a stack, if
one thread is popping the element on the stack then another thread would not be
able to pushing the element on the stack.
The following program demonstrates the synchronized method:
class Share extends Thread{
|
Output of the program is:
C:\nisha>javac SynThread.java C:\nisha>java SynThread Thread One: This Thread One: is Thread One: a Thread One: synchronized Thread One: variable Thread Two: This Thread Two: is Thread two: a Thread Two: synchronized Thread Two: variable |
In this program, the method "display( )" is synchronized that will be shared by both thread's objects at the time of program execution. Thus only one thread can access that method and process it until all statements of the method are executed.
Synchronized Blocks (Statements)
Another way of handling synchronization is Synchronized Blocks (Statements). Synchronized statements must specify the object that provides the native lock. The synchronized block allows execution of arbitrary code to be synchronized on the lock of an arbitrary object.
General form of synchronized block is:
synchronized (object reference expression) { // statements to be synchronized } |
The following program demonstrates the synchronized block that shows the same output as the output of the previous example:
class Share extends Thread{ synchronized(this){
|
Output of the Program
C:\nisha>javac SynStatement.java
C:\nisha>java SynStatement |