Google

Aug 22, 2014

What are the different ways a Java thread gets blocked or suspended? How will you debug Java threading issues?

1. It has been put to sleep for a set amount of time

 
   public void run(){
       try{
           while(true){
               this.sleep(1000);
               System.out.println("looping while");
            }
        }catch(InterruptedException ie){
        ie.printStackTrace();
  }
   }


2. The thread is suspended by call to wait( ), and will become runnable on a notify or notifyAll message.

 
class ConsumerProducer {

   private int count;
  
   public synchronized  void consume() {
       while(count == 0) {
          try {
        wait();
    }
     catch(InterruptedException ie){}
       }
       count--;   //consumed     
   }   


   public synchronized void produce() {
         count++;
   notify(); //notify the waiting consumer that count is incremented 
   }
   
}


3. Using join( ) method, which means waiting for a thread to complete. In the example below, the main thread that spawned worker threads t1 and t2 will wait on the t1.join() line until t1 has finished its work, and then will do the same for t2.join( ).

 
    Thread t1 = new Thread(new EventThread("event-1"));
    t1.start();
    Thread t2 = new Thread(new EventThread("event-2"));
    t2.start();

    while (true) {
        try {
           t1.join();
           t2.join();    
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
     }



4. Threads will be blocked on acquiring an intrinsic or explicit lock. Understanding Java locks and synchronized keyword.

5. Threads can get blocked on a long running I/O operations. For example, on a call  to long running database operation.

Threads block on I/O so that other threads may execute whilst the I/O operation is being performed.

class MyServer implements Runnable {
  public void run() {
    try {
       ServerSocket ss = new ServerSocket(PORT);
       while (!Thread.interrupted()){
           new Thread(new Handler(ss.accept())).start();
           // one thread per socket connection
           // every thread created this way will essentially block for I/O
   }
   } catch (IOException ex) { 
      ex.printStacktrace();
   }
 }
 
   //...
}


In Java 5 NIO (New I/O) was introduced to perform non-blocking I/O with selectors and channels.

Q. How will you go about debugging threads that are blocked?
A. Creating thread dumps.Thread dumps are very useful for diagnosing synchronization problems such as blocked threads causing deadlocks, thread starvation, etc.
  • The trick is to take 5 or 6 sets of thread dumps at an interval of 5 seconds between each to have a dump file that has 25 to 30 seconds worth of run time action. 
  • For thread dumps, use kill -3 in Unix and CTRL+BREAK in Windows. There are tools like Thread Dump Analyzer (TDA), Samurai, etc to derive useful information from the thread dumps to find where the problem is.
  • For example, Samurai colors idle threads in grey, blocked threads in red, and running threads in green. You must pay more attention to those red ones, as to why they are blocked for 5+ seconds.

Manually reviewing the code for any obvious thread-safety issues. There are static analysis tools like Sonar, ThreadCheck, etc for catching concurrency bugs at compile-time by analyzing their byte code.

List all possible causes and add extensive log statements and write test cases to prove or disprove your theories.

There are tools like JDB (i.e. Java DeBugger) where a “watch” can be set up on the suspected variable. When ever the application is modifying that variable, a thread dump will be printed.

There are dynamic analysis tools like jstack and JConsole, which is a JMX compliant GUI tool to get a thread dump on the fly. The JConsole GUI tool does have handy features like “detect deadlock” button to perform deadlock detection operations and ability to inspect the threads and objects in error states. Similar tools are available for other languages as well.

Labels: ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home