Sunday, 29 May 2016

How Thread.join() in Java works internally.

How join method works in Java.


join() method is used for waiting the thread in execution until the thread on which join is called is not completed.
Remember, the thread which will wait is the thread in execution and it will wait until the thread on which join method called is not completed.

How join method works internally.



Consider a scenario below and we will try to understand join() method by going through example.
package javabypatel;

public class ThreadJoinDemo extends Thread{
 static ThreadJoinDemo thread1;

 public void run(){
  try{
   synchronized(thread1){
    System.out.println(Thread.currentThread().getName()+" acquired a lock on thread1");
    Thread.sleep(5000);
    System.out.println(Thread.currentThread().getName()+" completed");
   }
  }
  catch (InterruptedException e){ }
 }

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

  synchronized(thread1){
   System.out.println(Thread.currentThread().getName()+" acquired a lock on thread1");
   Thread.sleep(1000);
   thread1.join();
   System.out.println(Thread.currentThread().getName()+" completed");
  }
 }
}

Output:
main acquired a lock on thread1
thread1 acquired a lock on thread1 //after 1 second this line is printed
thread1 completed //after 5 second this line is printed
main completed

In above example, we created 2 Threads,
  1. "main" thread
  2. "thread1" thread
Based on output, the flow went as shown below,




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 wont be visible in java thread API.

You may also like to see


Advanced Java Multithreading Interview Question-Answer.

Exception Handling Interview Question-Answer

Method Overloading - Method Hiding Interview Question-Answer

Type Casting Interview Questions In Java

How is ambiguous overloaded method call resolved in java

Method Overriding rules in Java

Interface interview questions and answers in Java

Enjoy !!!! 

If you find any issue in post or face any error while implementing, Please comment.

No comments:

Post a Comment