J2EEOnlineJ2EE





Java Multitasking  «Prev  Next»
Lesson 9Synchronization
ObjectiveDescribe how and when to use synchronization in threads.

Java Thread Synchronization

When you synchronize methods, you are indicating that only one thread can use that method at a time. If another thread wants to use a synchronized method currently in use, that thread must wait. Usually this works fine, but there is one scenario in which this can be disastrous and that is deadlock.

Deadlock:

Imagine that there are two threads, A and B. Thread A is waiting to access a synchronized method in thread B. However, this method is in use by thread B, so thread A must wait. Thread B, in turn, is waiting to access a synchronized method in thread A, and this method in thread A is also in use. Both thread A and thread B are waiting on each other. This is what is meant by a deadlock.
Consider the program shown below and select 1 of 4 options.
public class TestClass{
 static StringBuffer sb1 = new StringBuffer();
 static StringBuffer sb2 = new StringBuffer();
 public static void main(String[] args){
  new Thread(new Runnable(){
   public void run(){
    synchronized(sb1){
     sb1.append("X");
     synchronized(sb2){
      sb2.append("Y");
     }
    }
   System.out.println(sb1);
   }
  }
  ).start();
  new Thread(new Runnable(){
   public void run(){
    synchronized(sb2){
     sb2.append("Y");
     synchronized(sb1){
      sb1.append("X");
     }
    }
    System.out.println(sb2);
   }
  }
  ).start();
 }
} 

Select 1 option:
  1. It will print XX followed by YY
  2. It will print YY followed by XX
  3. It will print XY followed by YX
  4. The above code may result in a dead lock and so nothing can be said for sure about the output.



Answer: d
Explanation:
Consider the following situation: First thread acquires the lock of sb1 and appends X to sb1. Just after that the CPU stops this thread and starts the second thread. Observe that the first thread still has the lock of sb1. The second thread acquires the lock of sb2 and appends Y to sb2. Now it tries to acquire the lock for sb1. But its lock is already acquired by the first thread so the second thread has to wait.
Now, the CPU schedules the first thread. It tries to acquire the lock of sb2 but cannot get it because the lock is already acquired by the second thread. Here, you can see that both threads are waiting for each other to release the lock. So in effect both are stuck and this is a classic case of a Deadlock. Therefore, the output cannot be determined.
Synchronization allows your program to ensure that independent threads do not interfere with each other. The Town Hall application builds synchronization into its methods. In the next few pages, we will look at:
  1. Why synchronization is good in the town hall application
  2. How Java Performs synchronization
  3. How to Coordinate between threads using join()
Coordinating Java Threads - Quiz