Tread Synchronizing

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Thread Synchronization

Synchronization. At times when more than one thread try to access a shared resource, we need to
ensure that resource will be used by only one thread at a time. The process by which this is
achieved is called synchronization. The synchronization keyword in java creates a block of code
referred to as critical section.

Why we use Syncronization ?


If we do not use syncronization, and let two or more threads access a shared resource at the same
time, it will lead to distorted results.
Consider an example, Suppose we have two different threads T1 and T2, T1 starts execution and
save certain values in a file temporary.txt which will be used to calculate some result when T1
returns. Meanwhile, T2 starts and before T1 returns, T2 change the values saved by T1 in the file
temporary.txt (temporary.txt is the shared resource). Now obviously T1 will return wrong result.
To prevent such problems, synchronization was introduced. With synchronization in above case,
once T1 starts using temporary.txt file, this file will be locked(LOCK mode), and no other thread
will be able to access or modify it until T1 returns.

Using Synchronized Methods


Using Synchronized methods is a way to accomplish synchronization. But lets first see what
happens when we do not use synchronization in our program.
import java.io.*;

class Bucket
{
synchronized public void holdBucket(String Thname)
{
System.out.println("Bucket is holded by "+Thname);
for (int i = 0; i < 10; i++)
{
System.out.println(i);
try
{
Thread.sleep(400);
}
catch (Exception e)
{
System.out.println(e);
}
}
}

public class impBucket implements Runnable


{
String ThrdName;
Bucket bucket;
impBucket(String nm,Bucket b)
{

ThrdName=nm;
bucket=b;
}
public void run()
{
System.out.println(ThrdName+"Holds bucket");
bucket.holdBucket(ThrdName);
System.out.println(ThrdName+"Release bucket");

}
public static void main(String args[])
{
Bucket bucket= new Bucket();
Thread t1, t2,t3;
impBucket b1,b2,b3;
b1= new impBucket("Thread1",bucket);
b2= new impBucket("Thread2",bucket);
b3= new impBucket("Thread3",bucket);
t1= new Thread(b1);
t2= new Thread(b2);
t3= new Thread(b3);
t1.start();
t2.start();
t3.start();
}
}

Synchronized Keyword
To synchronize above program, we must synchronize access to the shared display() method, making
it available to only one thread at a time. This is done by using keyword synchronized with display()
method.
synchronized void display (String msg)

Using Synchronized block


If you have to synchronize access to an object of a class or you only want a part of a method to be
synchronized to an object then you can use synchronized block for it.
class First
{
public void display(String msg)
{
System.out.print ("["+msg);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println ("]");
}
}
class Second extends Thread
{
String msg;
First fobj;
Second (First fp,String str)
{
fobj = fp;
msg = str;
start();
}
public void run()
{
synchronized(fobj) //Synchronized block
{
fobj.display(msg);
}
}
}

public class Syncro


{
public static void main (String[] args)
{
First fnew = new First();
Second ss = new Second(fnew, "welcome");
Second ss1= new Second (fnew,"new");
Second ss2 = new Second(fnew, "programmer");
}
}

[welcome] [new] [programmer]


Because of synchronized block this program gives the expected output.

Difference between synchronized keyword and synchronized block


When we use synchronized keyword with a method, it acquires a lock in the object for the whole
method. It means that no other thread can use any synchronized method until the current thread,
which has invoked it's synchronized method, has finished its execution.
synchronized block acquires a lock in the object only between parentheses after the synchronized
keyword. This means that no other thread can acquire a lock on the locked object until the
synchronized block exits. But other threads can access the rest of the code of the method.

Which is more preferred - Synchronized method or Synchronized block?


In Java, synchronized keyword causes a performance cost. A synchronized method in Java is very
slow and can degrade performance. So we must use synchronization keyword in java when it is
necessary else, we should use Java synchronized block that is used for synchronizing critical section
only.
Interthread Communication
Java provide benefits of avoiding thread pooling using inter-thread communication. The wait(),
notify(), and notifyAll() methods of Object class are used for this purpose. These method are
implemented as final methods in Object, so that all classes have them. All the three method can be
called only from within a synchronized context.
• wait() tells calling thread to give up monitor and go to sleep until some other thread enters
the same monitor and call notify.
• notify() wakes up a thread that called wait() on same object.
• notifyAll() wakes up all the thread that called wait() on same object.

Difference between wait() and sleep()


wait() sleep()
called from synchronised block no such requirement
monitor is released monitor is not released
gets awake when notify() or notifyAll() does not get awake when notify() or notifyAll()
method is called. method is called
not a static method static method
sleep() method is simply used to put your thread on
wait() is generaly used on condition
sleep.

What are wait(), notify() and notifyAll() methods?

The Object class in Java has three final methods that allow threads to communicate about the
locked status of a resource. These are :
1. wait() : It tells the calling thread to give up the lock and go to sleep until some other thread
enters the same monitor and calls notify(). The wait() method releases the lock prior
to waiting and reacquires the lock prior to returning from the wait() method. The
wait() method is actually tightly integrated with the synchronization lock, using a feature
not available directly from the synchronization mechanism. In other words, it is not possible
for us to implement the wait() method purely in Java: it is a native method.

General syntax for calling wait() method is like this:


synchronized( lockObject )
{
while( ! condition )
{
lockObject.wait();
}

//take the action here;


}
2. notify() : It wakes up one single thread that called wait() on the same object. It should be
noted that calling notify() does not actually give up a lock on a resource. It tells a
waiting thread that that thread can wake up. However, the lock is not actually given up until
the notifier’s synchronized block has completed. So, if a notifier calls notify() on a
resource but the notifier still needs to perform 10 seconds of actions on the resource within
its synchronized block, the thread that had been waiting will need to wait at least another
additional 10 seconds for the notifier to release the lock on the object, even though
notify() had been called.

General syntax for calling notify() method is like this:


synchronized(lockObject)
{
//establish_the_condition;

lockObject.notify();

//any additional code if needed


}
3. notifyAll() : It wakes up all the threads that called wait() on the same object. The highest
priority thread will run first in most of the situation, though not guaranteed. Other things are
same as notify() method above.

General syntax for calling notify() method is like this:


synchronized(lockObject)
{
establish_the_condition;

lockObject.notifyAll();
}

You might also like