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.

Important Java Thread Interview Questions & Answers

Multithreading Tutorial.
Interview Questions on Threads in Java


Question 1. What are Threads in Java?

In Java, when a program requires more than one task to execute in parallel, say for example,
  1. Reading a data from a local file.
  2. Reading a data from remote connection.
When both of above task need to be executed in parallel at that time Threading will come in picture.
So Java Threads helps creating multiple independent path of execution within a program which can run parallely.  

Exception Handling Interview Questions.

Exception Handling in Java Tutorial.
Interview Questions on Exception Handling in Java


What is Exception handling?

Any program is a set of instructions executing in predefined sequence, but due to some Run-time Error or Exceptions program flow gets disturbed and gives erroneous result and to handle this un-expected behavior or condition is known as Exception handling. 

There are mainly 2 types of problems that can occur at run time,

How is ambiguous overloaded method call resolved in java?

How compiler resolves ambiguous method overloading call. OR
Which overloaded method will get selected for null parameter in java. OR
Important Java Interview Questions On Method Overloading OR
Method Overloading Tutorial


What is method overloading?

If a class have multiple methods with same name but with different parameters list, it is known as Method Overloading. Parameters lists should differ in either,
  1. Number of parameters.
  2. Data type of parameters.
  3. Sequence of data type of parameters. 

Construct a Binary Tree from In-order and Post-order traversals.

How to construct a Binary Tree from given In order and Post order traversals.


Let us first understand what we want to achieve? what is the input and what will be the expected output?

Question:
Two traversals are given as input,
  int inOrder[] =   {20, 30, 35, 40, 45, 50, 55, 60, 70};
  int postOrder[] = {20, 35, 30, 45, 40, 55, 70, 60, 50};
By using above 2 given In order and Post Order traversal, construct Binary Tree like shown below,

How HashSet works in Java? How HashSet eliminates duplicates in Java? HashSet Tutorial.

How HashSet works in Java?
How HashSet eliminates duplicates in Java?


This is very popular interview question for both beginners and experienced. HashSet internally uses HashMap for storing the data and retrieving it back. 
So if you know how HashMap works then it is very easy to understand how HashSet works.



Java Interview Questions

Java Interview Questions


Java interview questions and answers focused on "Method overriding and Method hiding".
There are interview questions on other topics like Multithreading, Exception Handling, Type Casting, Ambiguous Overloaded methods etc with detailed explanation on each question.

You will get link of all articles at bottom of this post.

Check whether a given string is an interleaving of two other given strings. (String 1 and String 2 contains unique characters)

Check whether a given string is an interleaving of two other given strings.
(Assume there is unique characters in both strings)



Lets understand what is the input and the expected output.



Print all interleavings of given 2 string.

Print all interleaving of given 2 string.


Lets understand what is the input and the expected output.

Check if number is Power of Two.

Check if number is power of 2.


Lets understand what is the input and the expected output.
If the number given to you is,
Case 1:
Number = 8
8 is power of 2 because 2^3 is 8

Case 2:
Number = 9

9 is not power of 2 because 2^3 is 8 and next number 2^4 is 16, So 9 will not fall in powers of 2. For better understand check the Value column in above image, it contains powers of 2 till 128.

1(2^0) , 2(2^1), 4(2^2), 8(2^3), 16(2^4).... are all powers of 2

Algorithm


For identifying whether the given number is power of 2, there are many approaches,

Approach 1

In this simple approach

STEP 1. Check if a number is perfectly divisible by 2 by doing (number % 2). If the number is 
               perfectly divisible by 2 then remainder is 0.

STEP 2. If the number is NOT perfectly divisible by 2 then remainder is not 0 and return from here 
               as number is not power of 2. 
               
               If the number is perfectly divisible by 2 then remainder is 0 and check whether the 
               remaining number (number / 2) is perfectly divisible by 2.

STEP 3. Repeat the steps until the number is 1.


This method requires O(log N) time complexity.

Approach 2


In this approach, We will use Bit manipulation.

Number which are power of 2 like 4, 8, 16, 32 etc has only one bit set in there binary representation.

and number which are one less like 3, 7, 15, 31 etc has all the bits set in there binary representation apart from bit set in 4, 8, 16, 32.

      1 0 0 0 0   (16) n
&   0 1 1 1 1   (15) n-1

---------------------------------------
      0 0 0 0 0


So if we do Bitwise AND of (number) & (number -1) and if the result is 0 than the number is power of 2 else not.


This method requires O(1) time complexity.

Java Program to check if a given number is power of 2 (Approach 1)


 
package javabypatel;

public class CheckNumberIsPowerOf2 {

 public static void main(String[] args) {
  System.out.println(powerOf2(1));
 }

 private static boolean powerOf2(int number){
  if(number<=0){
   return false;
  }
  
  while(number > 1){
   if(number % 2 != 0){
    return false;
   }
   number = number / 2;
  }
  return true;
 }

}



Java Program to check if a given number is power of 2 (Approach 2)


package javabypatel;

public class CheckNumberIsPowerOf2 {

 public static void main(String[] args) {
  System.out.println(powerOf2(1));
 }

 private static boolean powerOf2(int number){
     return (number > 0) && ((number & (number - 1)) == 0);
 }
}

(number > 0) is added for the case to check whether entered number is greater than 0. otherwise we have to separately check that condition. 

You may also like to see


Place N Queens on N×N chess board such that no two Queens attack each other.

0/1 Knapsack Problem solved using Iterative and Dynamic Programming

Stock Buy Sell to Maximize Profit.

Find Minimum length Unsorted Subarray, Sorting which makes the complete array sorted

Count trailing zeros in factorial of a number.

How to Detect loop in linked list.

Tower Of Hanoi Program in Java.

Print Matrix Diagonally OR Diagonal order of Matrix.

Transpose of Matrix Inplace

Implement Queue using One Stack in Java (Recursive Implementation)

SOAP Vs REST Web Service, when to use SOAP, When to use REST.


Enjoy !!!! 

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