J2EEOnlineJ2EE





Java Multitasking  «Prev 

How Java synchronizes Threads and what causes Deadlock

Use the synchronized keyword to stop a speaker's comments from becoming lost in the sands of time, we can indicate that only one speaker can add comments to the queue at a time. We declare the method to be synchronized.
Unlike many other programming languages, the Java Language Specification included explicit support for threading and concurrency.
While having language support for concurrency makes it easier to specify and manage constraints on shared data and the timing of operations across threads, it does not make the complexities of concurrent programming any easier to understand.

public synchronized void enqueue(Object elt) { 
}

How Java performs synchronization

Java does the bookkeeping so you do not have to. Here is what Java does for you.
Java associates a monitor, or lock, with each object and with each class. When a thread enters a synchronized instance method, that thread acquires the lock for that object. When a thread enters a synchronized class method, that thread acquires the lock for that class. When the thread exits the synchronized method, it releases the lock.
Once you call a synchronized method, any other call to a synchronized method for that instance or class must wait until the thread exits the synchronized method. The important concept to grasp here is that Java is performing this synchronization as part of the language. Java is handling all the checks and protections; all you have to do is use the correct keyword. With a synchronized method, Java can protect data that should be changed by only one thread at a time.
The synchronized keyword can be used with
  1. class (static) methods as well as
  2. instance methods.
In addition, this keyword can be used in the middle of code. This means that while the method itself is not synchronized, a portion of the method is. To use this technique, you must specify the object or class whose lock will be used to lock the code, as in:


void myMethod() {
 // . . . some code goes here
 synchronized (this) {
  // . . . locked code goes here
 }
}

Or, you can specify a class for the lock, as in:
 
synchronized (MyClass) {
  // . . . locked code goes here
}

Also, it is sometimes important to know that a thread releases the lock for a synchronized method when it calls wait(). This gives other threads a chance to change the conditions upon which the first thread is waiting.
Even though synchronizing methods is often a good thing, it does have its drawbacks. In particular, invoking a synchronized method is slow, and synchronizing methods sets up a disastrous situation called deadlock. This occurs when two threads are waiting on each other to finish a task.