Friday, November 1, 2019

When Together With How To Role The Wait() Together With Notify(), Nofityall() Methods Inwards Java? - Example Tutorial

When should you lot purpose the wait() together with notify method inwards Java is i of the many pop questions close the hold off together with notify methods from Java multithreading interview questions. One of the reasons for its popularity is that yet a lot of Java programmer combat to explicate together with write code using wait-notify methods.  Many Java developer solely knows around facts close the hold off together with notify methods similar that wait() together with notify() are defined inwards the java.lang.Object course of written report or you lot cannot telephone outcry upwards wait() without synchronization, agency without a synchronized block or synchronized method but doesn't actually know when together with how to purpose them.

In this article, nosotros volition endeavour to pair that gap past times going through a elementary event of classical Producer-Consumer Problem together with present you lot how you lot tin purpose them patch writing concurrent Java applications for the existent world.

First together with firstly you lot should know that wait(), notify(), together with notifyAll() are tools for inter-thread communication inwards Java. By using this method, you lot tin say a thread to halt working together with afterwards offset processing.

They are the essential edifice block of Java multi-threading applications. In the existent world, you lot tin purpose the wait() together with notify() method to implement a producer-consumer designing where most of the multi-threaded application falls. If you lot don't know much close them, I propose you lot bring together a key course of written report on Java threads like Threading Essentials Mini-Course past times Java Champion, Heinz Kabutz.




How to purpose the wait() together with notify() methods inwards Java

You tin purpose wait() together with notify() method to communicate betwixt multiple threads, for example, you lot tin say i thread to halt working from around other thread based upon around condition, afterwards you lot tin notify it to offset processing again.

One of the pop event of wait() together with notify() method is to solve the producer-consumer problem, where you lot tin accept either unmarried producer together with unmarried consumer or multiple producers together with unmarried consumer or only i producer together with multiple consumers.

In this example, you lot volition larn how to implement multiple producers together with unmarried consumer solutions using wait() together with notify() inwards Java. If you lot are non familiar alongside notify together with notifyAll method, you lot tin farther see The Complete Java Masterclass to larn more.

 together with notify method inwards Java is i of the many pop questions close the hold off together with notify  When together with How to purpose the wait() together with notify(), nofityAll() methods inwards Java? - Example Tutorial


Wait-Notify Example To Solve Producer-Consumer Problem 

package tool;   import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.TimeUnit;   /**  * Influenza A virus subtype H5N1 elementary Java Program to demonstrate how to purpose hold off  * together with notify() method ofr inter-thread communciation  * inwards Java.   */   public class Hello {     public static void main(String[] args) {     Queue<String> q = new LinkedList<>();     boolean exit = false;     Producer p = new Producer(q, exit);     p.start();     Consumer c = new Consumer(q, exit);     c.start();     }   }   class Producer extends Thread {   private volatile Queue<String> sharedQueue;   private volatile boolean bExit;     public Producer(Queue<String> myQueue, boolean bExit) {     this.sharedQueue = myQueue;     this.bExit = bExit;   }     public void run() {     while (!bExit) {       synchronized (sharedQueue) {         while (sharedQueue.isEmpty()) {           String detail = String.valueOf(System.nanoTime());           sharedQueue.add(item);           System.out.println("Producer added : " + item);           try {             System.out.println("Producer sleeping past times calling wait: " + item);             sharedQueue.wait();             System.out.println("Producer wake up: ");           } catch (InterruptedException e) {             e.printStackTrace();           }         }       }     }   } }   class Consumer extends Thread {   private volatile Queue<String> sharedQueue;   private volatile boolean bExit;     public Consumer(Queue<String> myQueue, boolean bExit) {     this.sharedQueue = myQueue;     this.bExit = bExit;   }     public void run() {       while (!bExit) {         synchronized (sharedQueue) {         while (!sharedQueue.isEmpty()) {           String detail = sharedQueue.poll();           System.out.println("Consumer removed : " + item);           System.out.println("Consumer notifying Producer: " + item);           sharedQueue.notify();         }       }     }   } }   Output: Producer added : 12275948008616 Producer sleeping past times calling wait: 12275948008616 Consumer removed : 12275948008616 Consumer notifying Producer: 12275948008616 Producer wake up:  Producer added : 12275948047960 Producer sleeping past times calling wait: 12275948047960 Consumer removed : 12275948047960 Consumer notifying Producer: 12275948047960 Producer wake up:  Producer added : 12275948082600 Producer sleeping past times calling wait: 12275948082600 Consumer removed : 12275948082600 Consumer notifying Producer: 12275948082600


What's Happening Here?

Producer thread is producing items, adding them into a queue together with thence going into wait() acre until consumer thread consumes it. When Consumer thread removes the items from the queue, it also notifies the Producer thread to offset producing again. 

That's why you lot meet an ordered output similar Producer added, Producer Sleeping, Consumer Removed, Consumer Notified, together with Producer Wakeup. In short, both Producer together with Consumer Thread are talking alongside each other using hold off together with notify method. 

If you lot take that hold off telephone outcry upwards thence the Producer thread volition expire on checking for the queue to expire waiting together with expire on wasting the CPU cycle. 

Similarly, if you lot take the notify telephone outcry upwards thence waiting Producer thread may never wake up.  Btw, if you lot accept problem agreement Producer-Consumer Problem thence I also propose taking a hold off at  the 
here to larn why

2) Always banking concern check the waiting status inwards a loop instead of if block inwards Java, meet here to larn why.

3) Remember, you lot tin wake upwards a waiting thread past times using interrupt() method but solely if your waiting thread handles the interrupted exception.

4) Prefer notifyAll() over notify() if you lot are inwards doubt, meet here to larn more.

5) Don't forget to telephone outcry upwards the wait() together with notify() method on the same shared object.


That's all close when to purpose the hold off together with notify method inwards Java. It's a perfect together with most native tool for inter-thread communication inwards Java. Influenza A virus subtype H5N1 proficient agreement of wait, notify, together with the notifyAll method goes a long way inwards writing a robust together with condom concurrent Java program. If you lot accept whatever problem agreement this problem, delight drib a Federal Reserve notation together with I'll endeavour to explain.

Further Learning
The Complete Java Masterclass
50+ Java Multithreading Interview Questions inwards Java
How to avoid deadlock inwards Java programs
Top v Courses to Learn Multithreading and Concurrency inwards Java
Multithreading together with Parallel Computing inwards Java


Thanks for reading this article thence far. If you lot similar this article thence delight part alongside your friends together with colleagues. If you lot accept whatever questions or feedback, delight drib a note. 

No comments:

Post a Comment