Simple Deadlock Program in Java

Simple java program to create Deadlock.


Deadlock describes a situation where two or more threads are blocked forever, waiting for each other.


Let's consider an example, in the office we have shared Printer and Scanner where Employees has ability to do scanning and printing.

1. John has bunch of documents that it wants to Print first and also want to take a Scan later.
(Print and Scan)

2. Michael has bunch of documents that it wants to Scan first and also want to take a Print later.
(Scan and Print)

Difference between process and thread

Difference between process and thread.


Point 1:
A process is an executing instance of an application.
Thread is independent path of execution within a process. Process can have multiple threads,

Point 2:
Threads itself is capable enough to do all the things a process does and thread is a part of process that is why thread can be termed as light-weight process.

Point 3:
Since all the Threads are part of a same Process they all share same memory allocated by Process.
Process use memory allocated by OS.

Point 4:
Inter-thread communication between threads is easy whereas Inter-process communication is difficult.

Point 5:
Processes have independent data and code segments.
Thread shares the data segment, code segment, files etc. with its peer threads.

Point 6:
Process switching is complex as compared to thread switching because of the amount of variables need to be maintained in both of the case.

Per process items Per thread items
Address space  Program counter
Global variables Registers
Open files Stack
Child processes State
Pending alarms
Signals and signal handlers
Accounting information

Difference between CountDownLatch and CyclicBarrier in Java

Difference between CountDownLatch and CyclicBarrier in Java?


Difference 1:

In CountDownLatch, main thread which mostly invokes latch.await() waits for other threads to call countDown() and count reaches 0. In CyclicBarrier, threads wait for each other to complete their execution and reach at common point after which barrier is opened.


Note in CountDownLatch, it is not necessary same thread calls latch.countDown() 10 times or 10 threads calling latch.countDown and making the counter 0 but in case of CyclicBarrier different threads should reach at the common barrier point.

Let's see example of CyclicBarrier

package com.javabypatel.practice;

import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierExample {
    
    public static void main(String args[]) {
        final CyclicBarrier cb = new CyclicBarrier(3, new Runnable(){
            @Override
            public void run(){
                System.out.println("Start the Game");
            }
        });

        Thread player1 = new Thread(new Player(cb), "Thread1");
        Thread player2 = new Thread(new Player(cb), "Thread2");
        Thread player3 = new Thread(new Player(cb), "Thread3");

        player1.start();
        player2.start();
        player3.start();
    }
}

class Player implements Runnable {

    private CyclicBarrier barrier;
    public Player(CyclicBarrier barrier) {
        this.barrier = barrier;
    }

    @Override
    public void run() {
        try {
            System.out.println(Thread.currentThread().getName() + " is waiting on barrier");
            barrier.await();
            System.out.println(Thread.currentThread().getName() + " has passed the barrier");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Output:
Thread1 is waiting on barrier
Thread2 is waiting on barrier
Thread3 is waiting on barrier
Start the Game
Thread3 has passed the barrier
Thread2 has passed the barrier
Thread1 has passed the barrier

Difference 2:

CountDownLatch can not be reused once count reaches 0. CyclicBarrier can be reinitialized once parties reaches 0.

Difference 3:

CountDownLatch calls countDown() method to reduce the counter where as CyclicBarrier calls await() method to reduce the counter. Note, await() method blocks the thread from further execution until all thread reaches to a common barrier, countDown() method doesn't block anything.

Difference 4:

CountDownLatch can not trigger common event when count reaches 0, that is when count reaches 0, it just unblocks the blocked thread and proceed with executing further instructions.

CyclicBarrier can trigger common event (Runnable) once it reaches to a barrier point.
Example: refer above

Difference 5:

CyclicBarrier is used for map-reduce kind of operations, like say we want to count population on India, so we will create say 4 threads which counts the population of East, West, North and South.

Each thread will count the population of its Region, we also need to merge the result when data from all threads is ready until which merging cannot be done.

We can create a CyclicBarrier and block the thread after it finds the count, so all threads are blocked after counting the population of its respective region, once all thread reaches barrier, it is broken and merger(Runnable event) can be executed to count the population.

CountDownLatch is used when we want all thread to reach at common event but doesn't necessarily want to block them at that point and they can proceed after signaling(latch.countDown()), Say for example, if we want to start the client file poller after database service(thread1) and ConnectionPoolService with 100 threads(thread2) is up, so we can wait for thread1 and thread2 to call countDown() after which blocked main thread can proceed with starting client file pooler.


You may also like to see


Advanced Java Multithreading Interview Questions & Answers

Type Casting Interview Questions and Answers In Java?

Exception Handling Interview Question-Answer

Method Overloading - Method Hiding Interview Question-Answer

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.

Difference between Join and CountDownLatch in Java

Difference between Join and CountDownLatch?



Difference 1:

Thread join method waits for other thread to finish before further executing current thread.
If t1.join is called in main thread, then main thread will wait at that point until t1 finishes its job.

CountDownLatch on the other end wait for its counter to reach 0 before executing current thread.
ExecutorService service = Executors.newFixedThreadPool(5);
final CountDownLatch latch = new CountDownLatch(3);

for(int i = 0; i < 5; i++) {
    service.submit(new Runnable() {
        public void run() {
            latch.countDown();
        }
    });
}

latch.await();

When latch.countDown is called, associated counter will be decremented and as soon as it reaches 0, main thread which was blocked at line latch.await() proceeds further.


Note:
Thread join method wait for joined thread to finish the execution before the main thread on which join method is called to starts its execution. Whereas in CountDownLatch, latch.await doesn't wait for the thread that calls latch.countDown() to be finished, it proceeds once the counter value reaches 0 and it has no association with the state of the thread that calls countDown().

Difference 2:

We can call join method when we have control over the threads but while using ExecutorService we don't have control over individual threads instead we deal with just submitting the task to framework and it internally manages threads in this situation using CountDownLatch is right approach.

Example above in difference 1 can be used as Reference.


Usage:

Example 1:
CountDownLatch is useful in Multiplayer games, Lets say we have a online chess game that can only be played when two player joins, in this case we will initialize the CountDownLatch to 2 and starts the game only after 2 threads(player) joins(calls countDown()).

Example 2:
Lets say we have some Timer task that we want to start only after all the modules of the application get loaded or when all the services is up.
 

You may also like to see


Advanced Java Multithreading Interview Questions & Answers

Type Casting Interview Questions and Answers In Java?

Exception Handling Interview Question-Answer

Method Overloading - Method Hiding Interview Question-Answer

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.

ReentrantLock interview questions in Java

ReentrantLock interview questions in Java


Reentrant lock is more feature rich than using synchronized method/block.

This post assume you have basic idea about Threads and synchronization in Java, If not I recommend going through below Multithreading articles first,
When using synchronized method or a synchronized block, process of lock acquisition and release is actually handled internally but with Reentrant Lock, programmer has full control over thread locks and thread locking management is on developer by explicitly calling lock and unlock method, so there is both advantages and disadvantages of this Reentrantlock.
reentrantlock interview questions in java
Reentrantlock interview questions in java

Question 1: What is the difference between ReentrantLock and Synchronized keyword in Java?


Time to wait for getting a Lock:

When a thread invoke synchronized method or a block, It has to first acquire a lock and then only it can proceed, there is no control to programmer over a time a thread should keep waiting for lock. 

Lets understand above point with an example, When thread 1 tries to call any synchronized method or synchronized block, It has to wait until some other thread say thread 2 release the lock on the same monitor. What if the thread 2 doesn't release the monitor due to some reason, How much time thread 1 has to wait, there is no control to the programmer till when Thread 1 will be waiting.

Using ReentrantLock which was introduced in jdk 1.5 under java.util.concurrent.locks package, We can provide a timeout till when thread should keep waiting for acquiring a lock and after that time thread will proceed with normal execution. this will give more control to threads while waiting for a lock instead of indefinitely waiting or getting blocked till lock is acquired.

Example: tryLock method,
  
Lock lock = new ReentrantLock();
lock.tryLock(long timeout, TimeUnit unit)
Complete trylock example in Java
package javabypatel;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadSafeArrayList<E> {
    public static void main(String[] args) throws Exception {
        final ReentrantLock lock1 = new ReentrantLock();
        final ReentrantLock lock2 = new ReentrantLock();

        String printerLock = "PrinterLock";
        String scannerLock = "ScannerLock";

        Runnable try1_2 = getRunnable(lock1, printerLock, lock2, scannerLock);
        Runnable try2_1 = getRunnable(lock2, scannerLock, lock1, printerLock);
        Thread t1 = new Thread(try1_2);
        t1.start();
        Thread t2 = new Thread(try2_1);
        t2.start();
    }

    private static Runnable getRunnable(final ReentrantLock lock1, final String lock1Name,
        final ReentrantLock lock2, final String lock2Name) {
        return new Runnable() {
            @Override
            public void run() {
                try {
                    if (lock1.tryLock(5, TimeUnit.SECONDS)) {
                        System.out.println(lock1Name + " acquired by thread " + Thread.currentThread());

                        Random rand = new Random();

                        if (lock2.tryLock(rand.nextInt(10), TimeUnit.SECONDS)) {
                            System.out.println(lock2Name + " acquired by thread " + Thread.currentThread());
                            Thread.sleep(2000);
                        } else {
                            System.out.println("Could not acquire " + lock2Name + " by thread " + Thread.currentThread());
                            lock1.unlock();
                            System.out.println(lock1Name + " released by thread " + Thread.currentThread());
                        }
                    } else {
                        System.out.println("Unable to acquire " + lock1Name + " by thread " + Thread.currentThread());
                    }
                } catch (InterruptedException e) {
                    System.out.println("I am interrupted" + Thread.currentThread());
                } finally {
                    if (lock1.isHeldByCurrentThread())
                        lock1.unlock();
                    if (lock2.isHeldByCurrentThread())
                        lock2.unlock();
                }
            }
        };
    }
}
Fairness policy:

When thread (say thread 1) calls synchronized method or synchronized block, it has to first acquire the monitor and then only can enter inside synchronized area. If monitor is acquired by other thread say thread 2 then thread 1 has to wait. 

Also, there can be many threads(say thread 1, thread 5, thread 8 etc) waiting for the same monitor. what will happen when thread 2 release the lock on monitor, which thread will be the next to execute among thread 1, thread 5, thread 8 waiting for lock? 

There is no guarantee which thread will get the control and that totally depends on scheduler, this leads to problem of thread (say thread 1) not getting monitor even though it is waiting for longest time among other threads for acquiring the lock and other thread (say thread 5) gets the monitor even if it just joined the waiting queue. ReentrantLock solves this problem by adding fairness policy while creating 
ReentrantLock  object.

While creating a ReentrantLock object, we can provide fairness property for making the lock fair. Fairness property provides lock to longest waiting thread, in case of contention. With fairness enabled, Threads get the lock in the order they requested it.

Example:
  
  ReentrantLock lock = new ReentrantLock(true);

Note: Performance is degraded by fairness policy.

LockInterruptibly

When thread 1 calls the synchronized method or synchronized block, it will be blocked until lock on the monitor is available. programmer don't have control to resume the blocked thread.
ReentrantLock provides a method called lockInterruptibly(), which can be used to interrupt the thread when it is waiting for lock. so that it can no longer in blocked state indefinitely.

void lockInterruptibly()
If thread is able to acquire lock then this method increments lock hold count by 1.
If the lock is with another thread then the current thread waits until it gets the lock or some other thread interrupts the thread.

lockinterruptibly example in java:
public class LockInterruptiblyExample{
 final ReentrantLock reentrantLock = new ReentrantLock();
 
 public void performTask() {
      try {
       reentrantLock.lockInterruptibly(); //wait till thread get the lock or till other thread interrupts
         //and you can control further execution from catch block
       try {
         //.....
       } finally {
      reentrantLock.unlock();
       }
      } catch (InterruptedException e) {
       e.printStackTrace();
      }
 }
} 


Number of Threads blocked on monitor:

Using synchronized method or block doesn't provide any mechanism to know how many threads are blocked to acquire a lock on monitor
Reentrant lock provides getQueueLength() method which return number of threads that may be waiting to acquire this lock in java.


Lock Unlock in different scope

With Synchronized keyword, lock need to be acquired and released at complete method level or at block level. Lets say when thread t1 tries to acquire multiple locks by calling multiple synchronized method, in that case multiple locks are acquired by t1 and they must all be released in the opposite order.

In ReentrantLock, locks can be acquired and released in different scopes, and allowing multiple locks to be acquired and released in any order.

Example:

ReentrantLock reentrantLock;

public void getA() {
  reentrantLock.lock();
}

public void getB() {
  reentrantLock.unlock();
}


More than one waiting condition

When lock is acquired using intrinsic lock by calling synchronized method/block, this threads then communicate using wait(), notify() and notifyAll() methods of Object class.

Condition allows inter thread communication when lock is acquired using extrinsic way by Lock interface. Condition defines methods such as await(), signal() and signalAll() for waiting and notifying.

Using synchronized block/method for a common monitor, there is no way to distinguish for what reason each thread is waiting, thread t1, t2, t3 might be blocked say for putting the data in the queue, other threads say t5, t6, t7, t8 might be waiting for reading data from the queue and they all are waiting on common monitor "queue".

Lets consider producer consumer situation, say we have a queue of size one and is full and t1, t2, t3 is blocked for putting the data in the queue, so they are in waiting state.
Now, t5, t6, t7, t8 tries to read data from the queue, lets say t5 would be reading the data in the queue, meanwhile t6, t7, t8 would be in waiting state.

After t5 read the data from the queue, it calls notifyAll, this call is to notify producers(t1,t2,t3) to put the data in the queue as there is a space now,
there are total 6 threads waiting for monitor "queue"
putting data in queue = t1, t2, t3,
reading data from queue = t4, t6, t7
currently monitor is held by executing thread = t5

when t5 calls notifyAll, there is no guarantee who is going to be wake up, might be thread t7 wake up and it has to go back to waiting state again as nothing is there to read, next time might be t4 gets a chance and again no use of t4 wakeup and it will go back to waiting state.
When someone from t1, t2 or t3 wakes up then only things would proceed.

If there is a way for t5 thread to notifyAll only to threads that want to put data to queue t1, t2 and t3 then it would be helpful. Using Condition that is possible.

With intrinsic lock using synchronized method/block there is no way to group the waiting threads waiting on a common monitor. with Condition, we can create multiple wait sets.

When you use Condition: await()/signal() you can distinguish which object or group of objects/threads get a specific signal.

Using Condition, we now have way to create more than one condition variable per monitor.
Monitors that use the synchronized keyword can only have one. This means Reentrant locks(implementation of Lock interface) support more than one wait()/notify() queue.

    private final Lock lock = new ReentrantLock();
    private final Condition queueEmpty = lock.newCondition();
    private final Condition queueFull = lock.newCondition();

    public void putData(int data) {
        lock.lock();
        try {
            while (queue is empty) {
                queueEmpty.await();
            }
            this.data = data;
            queueFull.signalAll();
                      
        } finally {
            lock.unlock();
        }
    }

    public void getData() {
        lock.lock();
        try {
            while (queue is full) {
                queueFull.await();
            }
            queueEmpty.signalAll();
        } finally {
            lock.unlock();
        }
    }


Now with queueFull.signalAll(), only threads those are waiting for this condition on same monitor "lock" will be awaked and rest will still be waiting.

Condition interface also comes with useful method that is:
boolean awaitUntil(Date deadline): Causes the current thread to wait until it is signaled or interrupted, or the specified deadline elapses.

Note: there is similar method wait(long timeInMilliseconds), but when there is System date change, above method will have impact while wait will keep waiting for provided timeInMilliseconds. So decide which is better in your situation.

Question 2. Does synchronized method and block are reentrant?

Yes. synchronized method, synchronized block and Reentrant lock are all reentrant in nature.

What is the meaning of Reentrant?
A reentrant lock is one where a process can claim the lock multiple times without blocking on itself.
In simple terms, ability to call the same synchronized method again and again without getting blocked is called reentrant.

Lets understand with example,
synchronized  void getA () {
    getB();
}

synchronized void getB () {
    getA();
}

What will happen if say Thread 1 calls obj.getA(), thread 1 will  acquire a lock on obj and call method getA(). inside which it calls getB()(which is obj.getB()), thread 1 already hold the lock on obj so it will call getB(), 
getB() call getA()(which is obj.getA()), thread 1 already hold a lock on obj so it is allowed to call the method getA() again. this is called Reentrant. same lock is claimed multiple times that is each time getA is called.


Question 3. Show simple example on how to write lock and unlock method of Reentrant Lock? 
public void getA() { 
      reentrantLock.lock(); 
      try{ 
          //...
      } catch(Exception e) { 
          e.printStackTrace(); 
      } finally { 
          reentrantLock.unlock(); 
      }     
} 




Question 4. Why ReentrantLock is called ReentrantLock?

ReentrantLock keep track of lock acquisition count associated with the lock.
when a call reentrantLock.lock() is made to acquire a lock and if the lock is obtained then the acquisition count variable is incremented to 1, stating that lock has been acquired one time till now.

Similarly, when a call reentrantLock.unlock() is made acquisition count variable is decremented by 1.
When the count reaches 0 then only other thread will be allowed to take the lock.

When a thread t1 acquires a reentrant lock inside method say getA() and make a call to another method say getB() from inside getA() which is also guarded by reentrant lock, in this case thread t1 will acquire a lock twice one for getA() method and one for getB() method. In this case, if a thread t1 that is already holding a lock is now acquiring it again inside getB(), the acquisition count is incremented to 2 and now the lock needs to be released twice to fully release the lock.

Let's see sample program,

package com.javabypatel.concurrency;

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockExample {
    public static void main(String[] args) {
        ReentrantLock reentrantLock = new ReentrantLock();

        Thread t1 = new Thread(new Printer("Thread1", reentrantLock));
        Thread t2 = new Thread(new Printer("Thread2", reentrantLock));

        t1.start();
        t2.start();
    }
}

class Printer implements Runnable {

    private String threadName;
    private ReentrantLock reentrantLock;

    Printer(String threadName, ReentrantLock reentrantLock) {
        this.threadName = threadName;
        this.reentrantLock = reentrantLock;
    }

    @Override
    public void run() {
        System.out.println("Thread " + threadName + " is waiting to get lock");
        reentrantLock.lock();
        try {
            System.out.println("Thread " + threadName + " acquired lock");
            getA();
        } finally {
            reentrantLock.unlock();
            System.out.println("Thread " + threadName + " released the lock and the lock held count is :"+reentrantLock.getHoldCount());
        }
    }

    public void getA() {
        System.out.println("getA :: Thread " + threadName + " is waiting to get lock");
        try {
            reentrantLock.lock();
            System.out.println("getA :: Thread " + threadName + " acquired lock");
            System.out.println("getA :: Lock count held by thread " + threadName + " : " + reentrantLock.getHoldCount());

        } finally {
            reentrantLock.unlock();
            System.out.println("getA :: Thread " + threadName + " released the lock and the lock held count is :"+reentrantLock.getHoldCount());
        }
    }
}


Output:

Thread Thread1 is waiting to get lock
Thread Thread1 acquired lock
getA :: Thread Thread1 is waiting to get lock
getA :: Thread Thread1 acquired lock
getA :: Lock count held by thread Thread1 : 2
getA :: Thread Thread1 released the lock and the lock held count is :1
Thread Thread1 released the lock and the lock held count is :0
Thread Thread2 is waiting to get lock
Thread Thread2 acquired lock
getA :: Thread Thread2 is waiting to get lock
getA :: Thread Thread2 acquired lock
getA :: Lock count held by thread Thread2 : 2
getA :: Thread Thread2 released the lock and the lock held count is :1
Thread Thread2 released the lock and the lock held count is :0

You can see lock held count should go back to 0 for another thread to acquire a lock.


You may also like to see


Advanced Java Multithreading Interview Questions & Answers

Type Casting Interview Questions and Answers In Java?

Exception Handling Interview Question-Answer

Method Overloading - Method Hiding Interview Question-Answer

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.

What is Thread in Java with example.

What is Thread in Java with example.


Java Thread is an independent path of execution within a program which can run in parallel with other existing Threads.

Lets try to understand above line with simple scenario and it will be more clear:

Threads in Real time scenario:
Suppose you want to count the population of a India, how will you approach? 

Note: There are 29 states in India.

Approach 1:


First approach is, you start with first state and count population of that state then you will start second state and so on for all 29 states. 
Once you have population of all the states, just sum the population count of all States.

Imagine the time it will take for you to do this as you are alone and you have to count population state by state.
 

Approach 2:

Second approach is, you called 29 people to help you out and you distributed the task of population count to 29 person, each person taking care of individual state. 
  1. Person 1 will take care of population count for State 1. 
  2. Person 2 will take care of population count for State 2 and so on.
Once you have population count of all the states, just sum the population count received from all 29 person and you are done.

Imagine the time it will take for you to do this as compared to Approach 1, surely it will be much less.

So that is what Thread does. In above scenario, you can consider 29 persons as 29 Threads who are doing their respective task of population count.


It is possible that Person 1 may finish population count for State 1 assigned to it much early than Person 2 doing population count for State 2 because State 1 might be small.
Person 2 will continue doing his task even after Person 1 finished early. 


In the similar way, Say If you have 2 Threads say Thread 1 and Thread 2. Thread 1 may complete its job early and Thread 2 will continue doing its job even after Thread 1 is done and they both execute separately. 

Now to relate it with Threads:
When you have task like above that needs to be run in parallel for faster processing at that time Threading will come in picture.

You can say, Java Threads helps creating multiple independent path of execution within a program which can run parallely.
Application Example: 
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 in parallel.

You may also like to see


Compress a given string in-place and with constant extra space.

Check whether a given string is an interleaving of String 1 and String 2.

Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord.

Serialize and Deserialize a Binary Tree

Advanced Multithreading Interview Questions In Java

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

Top 20 Java Interview Questions and Answers.

Top 20 Java Interview Questions and Answers.


Top 20 Java Interview Questions and Answers. Frequently asked core Java Interview Questions and Answers for freshers and experienced.

List of Top Java Interview Questions and Answers for freshers and experienced.

Top 25 Java Concurrency Interview Questions Answers for Freshers and Experienced.


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.  

How to run two thread one after another in java

how to run two thread one after another in java.


How to run two thread one after another in java. To execute threads one after another it needs to be synchronized. wait notify notifyAll is useful.

This is the famous interview question for the beginners, 
Write a program that creates 3 threads and prints alternate values in sequence.

Input: 
We have three Threads, ThreadA, ThreadB and ThreadC each printing "A", "B" and "C" repectively.

Expected Output:
 
A B C A B C A B C A ...... so on.

Printing Threads in Sequence in Java.


We have 3 threads as shown below,

ThreadA is printing "A" continuously. (ThreadA.java)
ThreadB is printing "B" continuously. (ThreadB.java) 
ThreadC is printing "C" continuously. (ThreadC.java)

If we will not synchronize above threads then the output order is not guaranteed and we may get output like 
A C B B B C A A B C A A C C .... or
A C C C C C A A B C B B B B .... or anything

but the desired output is A B C A B C A B C A B C A B C......

For this, we need to synchronize ThreadA, ThreadB and ThreadC? what does synchronize mean here? 
Synchronize in simple terms is to allocate a turn to ThreadA as when it should run, allocate a turn to ThreadB as when it should run, allocate a turn to ThreadC as when it should run.

We took one variable "flag" and synchronize 3 threads as below, 
If value of flag=1, then it is ThreadA's turn to print.
If value of flag=2, then it is ThreadB's turn to print.
If value of flag=3, then it is ThreadC's turn to print. 

Now question is,
what will ThreadA do if flag value is 2 or 3 ? ThreadA will wait() as it is not his turn.
what will ThreadB do if flag value is 1 or 3 ? ThreadB will wait() as it is not his turn..
what will ThreadC do if flag value is 1 or 2 ? ThreadC will wait() as it is not his turn.

Thread can call wait() method, but wait() method needs to be called on some object. 
In our case, we will create class "ResourceLock", which will be used as a lock for all 3 threads and wait() method will be called on object of "ResourceLock".

What is the task of ThreadA,
  1. ThreadA should first acquire lock on the object of "ResourceLock", 
  2. ThreadA should check whether value of flag is 1,
  3. If No, then wait().
    If Yes,
    then print "A" and set the flag value to "2" for marking ThreadB's task as next.
    Notify all the waiting threads by using notifyAll() method.
Once notified, all waiting Threads will be waked up, that is ThreadB and ThreadC will be awake now, but as the value of flag is 2, only ThreadB will be active and other Threads will again go in waiting state.

Java Program to execute Threads in sequential order.


 ThreadRunningInSequence.java
package javabypatel;

public class ThreadRunningInSequence {

    public static void main(String[] args) {

     ResourceLock lock = new ResourceLock();

        ThreadA a=new ThreadA(lock);
        ThreadB b=new ThreadB(lock);
        ThreadC c=new ThreadC(lock);

        a.start();
        b.start();
        c.start();
    }
}
ThreadA.java
package javabypatel;

public class ThreadA extends Thread{

 ResourceLock lock;

 ThreadA(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=1){
      lock.wait();
     }

     System.out.print("A ");
     Thread.sleep(1000);
     lock.flag = 2;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 1 :"+e.getMessage());
  }

 }

}


ThreadB.java
package javabypatel;

public class ThreadB extends Thread{

 ResourceLock lock;

 ThreadB(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=2){
      lock.wait();
     }

     System.out.print("B ");
     Thread.sleep(1000);
     lock.flag = 3;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 2 :"+e.getMessage());
  }

 }
}

ThreadC.java
package javabypatel;

public class ThreadC extends Thread{

 ResourceLock lock;

 ThreadC(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=3){
      lock.wait();
     }

     System.out.print("C ");
     Thread.sleep(1000);
     lock.flag = 1;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 3 :"+e.getMessage());
  }

 }
}


ResourceLock.java
package javabypatel;

public class ResourceLock{
 public volatile int flag = 1;
}

You may also like to see


Java Multithreading and Concurrency Interview Questions and Answers with Example

Advanced Multithreading Interview Questions In Java

How ConcurrentHashMap works and ConcurrentHashMap interview questions.

Count number of Bits to be flipped to convert A to B 

Count number of Set Bits in Integer. 

Check if number is Power of Two. 

Find all subsets of a set (Power Set). 

Skyline Problem in Java. 

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

Count trailing zeros in factorial of a number 

When to use SOAP over REST Web Service. Is REST better than SOAP? 

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

Difference between wait notify notifyall example in Java.

Difference between wait notify notifyall example in Java.


Difference between wait notify notifyall example in Java. lets see difference between wait notify notifyall example using sample Java program.

wait() :
Thread on which wait() method is called will go to waiting state by releasing the monitor(here monitor is nothing but object of any class).
Note: This thread will wake up only if some other thread calls either notify or notifyAll on same monitor.

notify() :
Thread on which notify() method is called will wake up one thread who is waiting on same monitor.

notifyAll() :
Thread on which notifyAll() method is called will wake up all threads who is waiting on same monitor.
 

We will understand wait(), notify(), notifyAll() with the help of below program that creates 3 threads and prints alternate values in sequence.

Input: 
We have three Threads, ThreadA, ThreadB and ThreadC each printing "A", "B" and "C" repectively.

Output:
 

A B C A B C A B C A ...... so on.

Printing Threads in Sequence in Java.


We have 3 threads as shown below,

ThreadA is printing "A" continuously. (ThreadA.java)
ThreadB is printing "B" continuously. (ThreadB.java) 
ThreadC is printing "C" continuously. (ThreadC.java)

If we will not synchronize above threads then the output order is not guaranteed and we may get output like 
A C B B B C A A B C A A C C .... or
A C C C C C A A B C B B B B .... or anything

but the desired output is A B C A B C A B C A B C A B C......

For this, we need to synchronize ThreadA, ThreadB and ThreadC? what does synchronize mean here? 
Synchronize in simple terms is to allocate a turn to ThreadA as when it should run, allocate a turn to ThreadB as when it should run, allocate a turn to ThreadC as when it should run.

We took one variable "flag" and synchronize 3 threads as below, 
If value of flag=1, then it is ThreadA's turn to print.
If value of flag=2, then it is ThreadB's turn to print.
If value of flag=3, then it is ThreadC's turn to print. 

Now question is,
what will ThreadA do if flag value is 2 or 3 ? ThreadA will wait() as it is not his turn.
what will ThreadB do if flag value is 1 or 3 ? ThreadB will wait() as it is not his turn..
what will ThreadC do if flag value is 1 or 2 ? ThreadC will wait() as it is not his turn.

Thread can call wait() method, but wait() method needs to be called on some object. 
In our case, we will create class "ResourceLock", which will be used as a lock for all 3 threads and wait() method will be called on object of "ResourceLock".

What is the task of ThreadA,
  1. ThreadA should first acquire lock on the object of "ResourceLock", 
  2. ThreadA should check whether value of flag is 1,
  3. If No, then wait().
    If Yes,
    then print "A" and set the flag value to "2" for marking ThreadB's task as next.
    Notify all the waiting threads by using notifyAll() method.
Once notified, all waiting Threads will be waked up, that is ThreadB and ThreadC will be awake now, but as the value of flag is 2, only ThreadB will be active and other Threads will again go in waiting state.


Java Program to execute Threads in sequential order.


 ThreadRunningInSequence.java

package javabypatel;

public class ThreadRunningInSequence {

    public static void main(String[] args) {

     ResourceLock lock = new ResourceLock();

        ThreadA a=new ThreadA(lock);
        ThreadB b=new ThreadB(lock);
        ThreadC c=new ThreadC(lock);

        a.start();
        b.start();
        c.start();
    }
}
ThreadA.java
package javabypatel;

public class ThreadA extends Thread{

 ResourceLock lock;

 ThreadA(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=1){
      lock.wait();
     }

     System.out.print("A ");
     Thread.sleep(1000);
     lock.flag = 2;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 1 :"+e.getMessage());
  }

 }

}


ThreadB.java
package javabypatel;

public class ThreadB extends Thread{

 ResourceLock lock;

 ThreadB(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=2){
      lock.wait();
     }

     System.out.print("B ");
     Thread.sleep(1000);
     lock.flag = 3;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 2 :"+e.getMessage());
  }

 }
}

ThreadC.java
package javabypatel;

public class ThreadC extends Thread{

 ResourceLock lock;

 ThreadC(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=3){
      lock.wait();
     }

     System.out.print("C ");
     Thread.sleep(1000);
     lock.flag = 1;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 3 :"+e.getMessage());
  }

 }
}


ResourceLock.java
package javabypatel;

public class ResourceLock{
 public volatile int flag = 1;
}


You may also like to see


Java Multithreading and Concurrency Interview Questions and Answers with Example

Advanced Multithreading Interview Questions In Java

How ConcurrentHashMap works and ConcurrentHashMap interview questions.

Count number of Bits to be flipped to convert A to B 

Count number of Set Bits in Integer. 

Check if number is Power of Two. 

Find all subsets of a set (Power Set). 

Skyline Problem in Java. 

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

Count trailing zeros in factorial of a number 

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

wait notify notifyall example in Java Thread.

wait notify notifyall example in Java.


wait notify notifyall example in Java Thread. how wait notify notifyAll works in Java. difference between wait, notify and notifyAll in java thread. 

wait() :
Thread on which wait() method is called will go to waiting state by releasing the monitor(here monitor is nothing but object of any class).
Note: This thread will wake up only if some other thread calls either notify or notifyAll on same monitor.

notify() :
Thread on which notify() method is called will wake up one thread who is waiting on same monitor.

notifyAll() :
Thread on which notifyAll() method is called will wake up all threads who is waiting on same monitor.
 

We will understand wait(), notify(), notifyAll() with the help of below program that creates 3 threads and prints alternate values in sequence.

Input: 
We have three Threads, ThreadA, ThreadB and ThreadC each printing "A", "B" and "C" repectively.

Output:
 

A B C A B C A B C A ...... so on.

Printing Threads in Sequence in Java.


We have 3 threads as shown below,

ThreadA is printing "A" continuously. (ThreadA.java)
ThreadB is printing "B" continuously. (ThreadB.java) 
ThreadC is printing "C" continuously. (ThreadC.java)

If we will not synchronize above threads then the output order is not guaranteed and we may get output like 
A C B B B C A A B C A A C C .... or
A C C C C C A A B C B B B B .... or anything

but the desired output is A B C A B C A B C A B C A B C......

For this, we need to synchronize ThreadA, ThreadB and ThreadC? what does synchronize mean here? 
Synchronize in simple terms is to allocate a turn to ThreadA as when it should run, allocate a turn to ThreadB as when it should run, allocate a turn to ThreadC as when it should run.

We took one variable "flag" and synchronize 3 threads as below, 
If value of flag=1, then it is ThreadA's turn to print.
If value of flag=2, then it is ThreadB's turn to print.
If value of flag=3, then it is ThreadC's turn to print. 

Now question is,
what will ThreadA do if flag value is 2 or 3 ? ThreadA will wait() as it is not his turn.
what will ThreadB do if flag value is 1 or 3 ? ThreadB will wait() as it is not his turn..
what will ThreadC do if flag value is 1 or 2 ? ThreadC will wait() as it is not his turn.

Thread can call wait() method, but wait() method needs to be called on some object. 
In our case, we will create class "ResourceLock", which will be used as a lock for all 3 threads and wait() method will be called on object of "ResourceLock".

What is the task of ThreadA,
  1. ThreadA should first acquire lock on the object of "ResourceLock", 
  2. ThreadA should check whether value of flag is 1,
  3. If No, then wait().
    If Yes,
    then print "A" and set the flag value to "2" for marking ThreadB's task as next.
    Notify all the waiting threads by using notifyAll() method.
Once notified, all waiting Threads will be waked up, that is ThreadB and ThreadC will be awake now, but as the value of flag is 2, only ThreadB will be active and other Threads will again go in waiting state.


Java Program to execute Threads in sequential order.


 ThreadRunningInSequence.java

package javabypatel;

public class ThreadRunningInSequence {

    public static void main(String[] args) {

     ResourceLock lock = new ResourceLock();

        ThreadA a=new ThreadA(lock);
        ThreadB b=new ThreadB(lock);
        ThreadC c=new ThreadC(lock);

        a.start();
        b.start();
        c.start();
    }
}
ThreadA.java
package javabypatel;

public class ThreadA extends Thread{

 ResourceLock lock;

 ThreadA(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=1){
      lock.wait();
     }

     System.out.print("A ");
     Thread.sleep(1000);
     lock.flag = 2;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 1 :"+e.getMessage());
  }

 }

}


ThreadB.java
package javabypatel;

public class ThreadB extends Thread{

 ResourceLock lock;

 ThreadB(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=2){
      lock.wait();
     }

     System.out.print("B ");
     Thread.sleep(1000);
     lock.flag = 3;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 2 :"+e.getMessage());
  }

 }
}

ThreadC.java
package javabypatel;

public class ThreadC extends Thread{

 ResourceLock lock;

 ThreadC(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=3){
      lock.wait();
     }

     System.out.print("C ");
     Thread.sleep(1000);
     lock.flag = 1;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 3 :"+e.getMessage());
  }

 }
}


ResourceLock.java
package javabypatel;

public class ResourceLock{
 public volatile int flag = 1;
}

You may also like to see


Java Multithreading and Concurrency Interview Questions and Answers with Example

Advanced Multithreading Interview Questions In Java

How ConcurrentHashMap works and ConcurrentHashMap interview questions.

Given an array of integers. All numbers occur thrice except one number which occurs once. Find the number in O(n) time & constant extra space. 

Count number of Bits to be flipped to convert A to B 

Count number of Set Bits in Integer. 

Check if number is Power of Two. 

Find all subsets of a set (Power Set). 

Skyline Problem in Java. 

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

Running Threads In Sequence in Java

Running Threads In Sequence in Java. OR
Run Threads Sequentially in Java. OR
To Execute the Threads one after another in Java. OR
Synchronizing Threads in Java OR
Java Program to execute Threads in sequential order.


Running Threads In Sequence in Java. for sequential execution or to execute threads one after another in Java, threads must be Synchronized in Java. 

This is the famous interview question for the beginners, 
Write a program that creates 3 threads and prints alternate values in sequence.

Input: 
We have three Threads, ThreadA, ThreadB and ThreadC each printing "A", "B" and "C" repectively.

Expected Output:
 
A B C A B C A B C A ...... so on.

Printing Threads in Sequence in Java.


We have 3 threads as shown below,

ThreadA is printing "A" continuously. (ThreadA.java)
ThreadB is printing "B" continuously. (ThreadB.java) 
ThreadC is printing "C" continuously. (ThreadC.java)

If we will not synchronize above threads then the output order is not guaranteed and we may get output like 
A C B B B C A A B C A A C C .... or
A C C C C C A A B C B B B B .... or anything

but the desired output is A B C A B C A B C A B C A B C......

For this, we need to synchronize ThreadA, ThreadB and ThreadC? what does synchronize mean here? 
Synchronize in simple terms is to allocate a turn to ThreadA as when it should run, allocate a turn to ThreadB as when it should run, allocate a turn to ThreadC as when it should run.

We took one variable "flag" and synchronize 3 threads as below, 
If value of flag=1, then it is ThreadA's turn to print.
If value of flag=2, then it is ThreadB's turn to print.
If value of flag=3, then it is ThreadC's turn to print. 

Now question is,
what will ThreadA do if flag value is 2 or 3 ? ThreadA will wait() as it is not his turn.
what will ThreadB do if flag value is 1 or 3 ? ThreadB will wait() as it is not his turn..
what will ThreadC do if flag value is 1 or 2 ? ThreadC will wait() as it is not his turn.

Thread can call wait() method, but wait() method needs to be called on some object. 
In our case, we will create class "ResourceLock", which will be used as a lock for all 3 threads and wait() method will be called on object of "ResourceLock".

What is the task of ThreadA,
  1. ThreadA should first acquire lock on the object of "ResourceLock", 
  2. ThreadA should check whether value of flag is 1,
  3. If No, then wait().
    If Yes,
    then print "A" and set the flag value to "2" for marking ThreadB's task as next.
    Notify all the waiting threads by using notifyAll() method.
Once notified, all waiting Threads will be waked up, that is ThreadB and ThreadC will be awake now, but as the value of flag is 2, only ThreadB will be active and other Threads will again go in waiting state.

Java Program to execute Threads in sequential order.


 ThreadRunningInSequence.java
package javabypatel;

public class ThreadRunningInSequence {

    public static void main(String[] args) {

     ResourceLock lock = new ResourceLock();

        ThreadA a=new ThreadA(lock);
        ThreadB b=new ThreadB(lock);
        ThreadC c=new ThreadC(lock);

        a.start();
        b.start();
        c.start();
    }
}
ThreadA.java
package javabypatel;

public class ThreadA extends Thread{

 ResourceLock lock;

 ThreadA(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=1){
      lock.wait();
     }

     System.out.print("A ");
     Thread.sleep(1000);
     lock.flag = 2;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 1 :"+e.getMessage());
  }

 }

}


ThreadB.java
package javabypatel;

public class ThreadB extends Thread{

 ResourceLock lock;

 ThreadB(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=2){
      lock.wait();
     }

     System.out.print("B ");
     Thread.sleep(1000);
     lock.flag = 3;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 2 :"+e.getMessage());
  }

 }
}

ThreadC.java
package javabypatel;

public class ThreadC extends Thread{

 ResourceLock lock;

 ThreadC(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=3){
      lock.wait();
     }

     System.out.print("C ");
     Thread.sleep(1000);
     lock.flag = 1;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 3 :"+e.getMessage());
  }

 }
}


ResourceLock.java
package javabypatel;

public class ResourceLock{
 public volatile int flag = 1;
}

You may also like to see


Java Multithreading and Concurrency Interview Questions and Answers with Example

Advanced Multithreading Interview Questions In Java

How ConcurrentHashMap works and ConcurrentHashMap interview questions.

Given an array of integers. All numbers occur thrice except one number which occurs once. Find the number in O(n) time & constant extra space. 

Count number of Bits to be flipped to convert A to B 

Count number of Set Bits in Integer. 

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

Count trailing zeros in factorial of a number 

When to use SOAP over REST Web Service. Is REST better than SOAP? 

Tower Of Hanoi Program in Java. 

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