Thread Synchronization Deadlock


Thread Synchronization Deadlock

Summary: By the end of this tutorial "Thread Synchronization Deadlock", you will come to know what is deadlock and how to avoid it. Synchronization is explained in simple terms and code. Start reading.

Introduction Thread Basics

Generally, one thread accesses one source of data (or to say, its own source) like your thread accesses your bank account. Sometimes, it may be needed multiple threads to access the same source of data like all the partners of a business may be acting on the joint bank account at the same time. When multiple threads access or share, there may be data corruption or inconsistency.

To avoid data inconsistency, a concept called synchronization comes. The literature meaning of synchronization is putting the events in an order. synchronized is a keyword of Java used as access modifier. A block of code or a method can be synchronized. The advantage of synchronization is only one thread is allowed to access the source and other threads are made to wait until the first thread completes its task (of accessing the source). This is known as a thread safe operation.

Synchronization is a way of inter-thread communication (another is join()). In the following snippet of code, whole method is synchronized.

public synchronized void update(int account, double withdrawAmount)
{
                                               // some JDBC code
  balance = balance - withdrawAmount;          // 1st statement
  System.out.println("Best Wishes");           // 2nd statement
}

In the following snippet, only one line of code is synchronized and all the remaining code is untouched (not synchronized).

public void withdraw(int account, double withdrawAmount)
{
  synchronized(this)
  {                                            // some JDBC code
    balance = balance - amount;                // 1st statement
  }
  System.out.println("Best Wishes");           // 2nd statement
}

Synchronization makes a program to work very slow as only one thread can access the data at a time. Designers advice to synchronize only the important and critical statements of the code. Do not synchronize unnecessarily.

In the above code, first statement is critical and the second is not. For this reason, in the second snippet, only first statement is synchronized. This increases the performance to some extent.

More on Thread Synchronization Deadlock – Thread Regulation

To explain the affect of synchronization, a small program is taken where 100 threads are created and iterated 10,000 times each. Each iteration increments the variable k by one and decrements by one. That is, at the end, the value should not be changed; should remain as zero, the default value for an unassigned instance variable.

public class SynchDemo implements Runnable 
{
  static int k;                                 // value default is 0
  public void run() 
  {
    synchronized(this)
    {
      for(int i = 0; i < 10000; i++) 
      {
        k++;		                        // increments by one
        k--;                                    // decrements by one
      }
    }
  }
  public static void main(String[] args) throws Exception 
  {
    SynchDemo sd = new SynchDemo();
    Thread bundle[] = new Thread[100];
    for(int i=0; i


Thread Synchronization Deadlock
Output screen on Thread Synchronization Deadlock

An array of 100 threads by name bundle is created. In a for loop they are initialized and started. In each iteration k is incremented and at the same time decremented, so that the value of k is unchanged.

The screenshot displays k is always 0 for any number times of execution. Just remove, the synchronized(this) statement and observe different outputs. Why this happens? How synchronization mechanism works internally? Let us see.

wait(), notify() and notifyAll()

These methods are defined in Object class inherited by every class so that every Java class can make use of these methods. When a thread accesses the synchronized code, the JVM calls wait() method. With this method call, the resource is locked so that no other thread is allowed to access. All the threads requiring the resource should wait in a queue outside. When the accessing thread job is over, it calls notify() or notifyAll() method and thus relinquishes the lock. Now JVM allows one of the waiting threads to access the resource. Again this thread calls wait() method and locks. As only one thread is allowed to access, the program runs very slow. wait(), notify() and notifyAll() methods are useful with synchronization only; outside they do not have any meaning. The electronics people say, the synchronization is nothing but applying monitor concept.

Remember, Vector methods are synchronized and ArrayList methods are not. Similarly, StringBuffer methods are synchronized and SringBuilder methods are not. Now the programmer has got choice to choose depending on the code necessity. Synchronization mechanism is very useful to control the scheduling of threads.

Starvation and Deadlock

These are the two problems that may creep into the programming code if the programmer is not aware of these concepts.

  1. Your style of programming should allow fairly each thread to get microprocessor time; this is known as fair system. A fair system does not allow a thread to get starved of processor time. A starved thread is the one that does not get processor for a long time. A starved thread cannot give the output fast.
  2. After starvation, another problem with threads is deadlock. When one thread depends on another for their execution, a deadlock occurs. When two threads are holding locks on two different resources, one thread would like to have other's source, a deadlock occurs. Deadlock is the result of poor programming code and is not shown by a compiler or execution environment as an exception. When exists, the program simply hangs and programmer should take care of himself.

Note: A class as a whole cannot be synchronized. That is, synchronized class declaration raises compilation error.

33 thoughts on “Thread Synchronization Deadlock”

  1. Gud Afternoon Respected Sir

    The above program has an Logical Error. I run it and tested it. The synchronized block never runs and the println statement in the last prints default value 0;

    Sir, I made following program which never printed any thing. Sir, please also explain why anonymous block is not being executed.

    public class TestAgain implements Runnable
    {

    public void run()
    {
    {
    System.out.println(“DN follows way2java.com”);

    }
    }
    public static void main(String[] args) throws Exception
    {
    SynchDemo sd = new SynchDemo();
    Thread bundle[] = new Thread[101];

    for(int i = 0; i < bundle.length; i++)
    {
    bundle[i] = new Thread(sd);
    bundle[i].start();
    }

    }
    }

    Regards

    Dn

  2. SIr,

    it is said above that wait() method is called by JVM to put a lock on the synchronized block (guarded block). And when the execution is over, it (the thread) will invoke either notify() or notifyAll() method to release the lock thus to allow other thread to gain the lock.

    But in docs.oracle.com pages for multi threading, it is said that the wait() method suspends the execution of a current thread until it receives a notifyAll() message from other thread to gain lock.

    “When wait is invoked, the thread releases the lock and suspends execution. At some future time, another thread will acquire the same lock and invoke Object.notifyAll, informing all threads waiting on that lock that something important has happened:”

    This is really confusing for me. Will you please clarify my doubt ?

  3. Sir you explained very well, i understand the topic .sir can you tell me by doing spring in java can we get a job, or servlet and jsp. sir tell me which on is best.

  4. balakrishna chowdary

    sir as a fresher i got good knowledge from way2java.com
    but i want some real time projects with good explanation as in way2java.com,
    ” because there are no calls for freshers so i want to get a good experience from your real time projects, to get the job on core java”

  5. Thanks sir to giving this wonderful site.Its awesome site to all java guys…most experienced guys also need some fine tune….. guys go through this site and make your self more brilliant..

  6. This is really good website for Java students as it s described each and every topic in detailed way.

    Thank u so much sir for providing such a good explanation on Java.

  7. way2java…………. is superb website to learn java.All the concepts were explained here easy manner and everybody can understand those concepts……………

Leave a Comment

Your email address will not be published.