How Java synchronizes Threads
What causes Deadlock
Use the
synchronized[1] 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
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.
[1]synchronized:
The Java language provides the synchronized keyword. In comparison with other threading systems, this
keyword allows the programmer access to a resource that is very similar to a mutex lock.