Monday, May 30, 2016

Internal representation of Thread join()


package com.javadsalgo;

class ThreadJoinDemo extends Thread {
     static ThreadJoinDemo thread1;

     public void run() {
           try {
           synchronized (thread1) {
           System.out.println(Thread.currentThread().getName()+ "                  acquired a lock on thread1");
           System.out.println("Going to sleep for 5 minutes");
           System.out.println("If thread1 is locked ?                              "+Thread.holdsLock(thread1));
           Thread.sleep(5000);
           System.out.println(Thread.currentThread().getName()+ "                  completed");
           // System native call invokes thread1.notifyAll(), so return            goes to main thread
                }
           } catch (InterruptedException e) {
       }
     }

     public static void main(String[] ar) throws Exception {
           thread1 = new ThreadJoinDemo();
           thread1.setName("thread1");
           thread1.start();

           synchronized (thread1) {
           // main thread will enter and acquire the lock on thread1.
           System.out.println(Thread.currentThread().getName() + "                  acquired a lock on inner thread1");
           System.out.println("Going to sleep for 2 minutes");
           Thread.sleep(2000);
           System.out.println("If thread1 is locked                                ?"+Thread.holdsLock(thread1));
           /*
           * join() internally calling thread1.wait(),which means                    main thread executing the code will release the lock on                  thread1 and go on waiting state...Entered to run()*/
           thread1.join();
           System.out.println(Thread.currentThread().getName() + "                  completed");
           }
           System.out.println("If thread1 is locked                                ?"+Thread.holdsLock(thread1));
     }
}

Output:

main acquired a lock on inner thread1
Going to sleep for 2 minutes
If thread1 is locked ?true
thread1 acquired a lock on thread1
Going to sleep for 5 minutes
If thread1 is locked ?true
thread1 completed
main completed
If thread1 is locked ?false

Who call notify/notifyAll in case of thread waiting on join method?
After run() method of thread is completed, it doesn't mean thread task is completed, 
It has to do many other tasks like 
  1. Destroying the associated stack, 
  2. Setting the necessary threadStatus etc.
One of the task is notifying the waiting threads, So that Thread waiting on join() method will be notified that thread has completed its task and joined threads can resume.

Above task are executed inside native thread call, so it won't be visible in java thread API.

References: http://javabypatel.blogspot.in/2016/05/how-thread-join-method-works-internally-iava.html

2 comments: