Showing posts with label thread. Show all posts
Showing posts with label thread. Show all posts

Friday, November 1, 2019

Why Wait() Together With Notify() Method Should Live On Called Within A Loop Inwards Java?

If yous create got used wait() together with notify() method inward Java together with hence yous know that the criterion idiom of calling wait() method uses a loop, but create got yous ever thought why? This is fifty-fifty advised past times none other than Joshua Bloch, a Java guru together with writer of pop producer-consumer problem, the waiting status for producer thread could survive written equally :

if(queue.isFull()){     queue.wait()   }   queue.add(item);

This says if the queue is total together with hence wait, otherwise insert an chemical component division into the queue. This looks fine at kickoff sight but when yous holler upwardly through nigh this inward a multi-threaded scenario, yous volition location the employment together with that's what yous volition acquire inward this article.

 Btw, this is my minute article on exploring how to locomote the wait-notify method inward Java. Earlier I create got written nigh why hold off together with notify is called from the synchronized context together with today you'll acquire why a loop is necessary for the wait-notify block. If yous haven't read that article, yous may detect it interesting together with useful.




What is the employment using if block amongst wait-notify inward Java?

This industrial plant fine inward ideal condition, but the programming basis is non e'er ideal. In an ideal condition, your thread volition exclusively wake upwardly if consumer thread has consumed 1 chemical component division together with directly the queue is non full, but inward the existent world, the waiting thread tin survive woken upwardly fifty-fifty if the status has non changed similar an evil thread sends an wrong notification.

If yous locomote the if block together with hence yous are non going to banking concern fit the waiting status 1 time to a greater extent than earlier start processing or adding but about other detail inward the queue. In that case, yous cease upwardly putting 1 to a greater extent than chemical component division inward the queue which is full, that could create error or exception.

This is why yous should e'er banking concern fit the waiting status inward a loop instead of if block.

There is but about other scenario, where multiple producers are waiting for a location inward the queue. If a user called notifyAll() together with informed all waiting threads nigh the 1 location beingness available.

After receiving this notification, 1 of the thread volition go for it together with fill upwardly that location but when other thread gets wake-up the location is already filled. If yous don't banking concern fit the status inward the loop together with hence yous cease upwardly adding to a greater extent than elements inward the already total queue.

When yous banking concern fit the waiting status inward the loop yous ensure that thread volition exam the status afterwards it wakes upwardly to encounter if the status however holds or not. If yous are non familiar amongst notify together with notifyAll method, yous tin farther see The Complete Java Masterclass to acquire more.

 method inward Java together with hence yous know that the criterion idiom of calling  Why wait() together with notify() method should survive called within a loop inward Java?



Reasons due to which a thread tin wake upwardly inward Java

Misdelivered notification: 
The gild inward which Java threads execute afterwards receipt of a notifyAll() holler for is unspecified. Which agency it's possible that an unrelated thread could start executing together with discovery that its status predicate is satisfied. Consequently, it could resume execution despite beingness required to stay dormant.

Spurious wakeups: 
Certain Java Virtual Machine (JVM) implementations are vulnerable to spurious wakeups that upshot inward waiting threads waking upwardly fifty-fifty without a notification

This is equally good truthful for await() method which is a novel method for Condition class but similar to wait().


The wrong way to locomote the wait() method


synchronized (object) {     if (condition does non hold) {        object.wait();     }     // Proceed when status holds   }


The right way to locomote the wait() method:

synchronized (object) {      while (condition does non hold) {        object.wait();      }      // Proceed when status holds   }


That's all nigh why wait() method should survive called within the loop inward Java instead of if block. As I create got said before, fifty-fifty the Java guru, Joshua Bloch, who has written many commutation classes of the java.lang package has advised this inward his classic Effective Java book, a must read for whatsoever serious Java programmer. It volition assist yous to avoid whatsoever such mistakes inward your day-to-day programming task.

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

Thanks for reading this article hence far. If yous similar this article together with hence delight portion amongst your friends together with colleagues. If yous create got whatsoever questions or feedback together with hence delight portion amongst your friends together with colleagues.

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. 

Right Fashion To Create, Showtime As Well As Destination A Novel Thread Inwards Java

One of the most of import business for a Java developer is to larn multi-threading together with larn it correctly. There are to a greater extent than Java developers who know multi-threading incorrectly than the programmer who doesn't know at all. In guild to larn it correctly, y'all demand to get-go it from scratch, I hateful the most cardinal concepts of multithreading similar how to do create, start, together with halt a novel thread inwards Java. I am certain y'all already know that every bit y'all direct maintain done that a lot of fourth dimension but it's worth remembering few facts to non repeat the mistakes many programmers do when they write multithreading code inwards Java. In this article, we'll run across a twain of those, mainly acre creating, starting, together with halt threads inwards Java. So fasten your seatbelt together with let's become niggling deep into threads inwards Java.



1. Use start() instead of run()

get-go creates a novel thread together with thus execute the code on that thread acre run only execute the code inwards the thread which calls the run() method.  I direct maintain discussed this already. See this article for a consummate discussion.


2. Use Runnable instead of Thread

There are 2 ways to do a Task for the thread, something which tin endure executed inwards parallel, either past times implementing Runnable interface together with overriding run() method or past times extending Thread flat together with putting your code within run() method there. Don't acquire confused betwixt these 2 run() method they are same Since Thread implements the Runnable interface it gets it from there.

An Example of Creating together with Starting Thread inwards Java

import java.util.Arrays;

public flat ThreadBasics{

    populace static void main(String args[]) {

        // instance of Runnable implementation for threads
        ParallelTask business = novel ParallelTask();
     
     
        // This volition solely do instance of Thread class
        // it volition non get-go until y'all telephone phone start() method
        Thread T1 = novel Thread(task);
        Thread T2 = novel Thread(task);
     
        // Starting T1 together with T2 thread
        T1.start();
        T2.start();  
   
    }
 
}

/*
 * Always role Runnable to lay code which y'all desire to execute parallel
 * Using multiple threads.
 */
class ParallelTask implements Runnable{

    @Override
    populace void run() {
       System.out.println(Thread.currentThread().getName() + " is executing ParallelTask");
     
    }
 
}

Output
Thread-0 is executing ParallelTask
Thread-1 is executing ParallelTask



How to do Daemon Thread inwards Java

There are 2 kinds of threads inwards Java, user thread or daemon thread. Some people every bit good similar to say daemon or non-daemon. Difference betwixt a daemon together with a user thread is that a user thread runs until the run() method completes either past times ordinarily or due to whatsoever Exception together with prevents your Java application from exiting.

On the other hand, daemon thread volition non proceed your Java programme endure if all user threads already finished execution. As presently every bit concluding user thread completes its execution, daemon thread dies, fifty-fifty if they are executing code inwards their run() method.

By default whatsoever thread, it derives its daemon condition from the thread which creates it, that's why whatsoever thread created past times the principal thread is ever non-daemon, unless together with until y'all become far daemon explicitly past times calling the setDaemon() method.

to give y'all an instance let's alter the before instance to innovate a 3-second slumber inwards the run() method of ParallelTask class, this volition foreclose brand thread running from longer duration. If both T1 together with T2 are non-daemon user threads thus your Java programme volition non dismiss until T1 together with  T2 goal execution.

On the other hand, if y'all brand them daemon, your Java programme volition goal every bit presently every bit your principal thread finishes. Here is the screenshot which volition brand things clear.

It volition fifty-fifty impress the next lines before Java programme finishes but inwards instance of daemon thread, the programme volition endure abruptly terminated together with impress statements from T1 together with T2 volition non endure printed.



Main Thread is finished
Thread-1 is finished
Thread-0 is finished


 One of the most of import business for a Java developer is to larn multi Right Way to Create, Start together with Stop a New Thread inwards Java





Use Volatile variable to Stop Thread inwards Java

Unfortunately, at that topographic point is no instantly way to halt the thread inwards Java. There was a stop() method inwards java.lang.Thread flat but it was long deprecated. This agency the solely way to halt a thread is to inquire him to come upwardly out from it's run execution is to get

Some best practices which volition help y'all to write ameliorate multi-threading code
1. Aways Name your Thread
2. Prefer Thread Pool vs Thread

That's all virtually how to create, get-go together with halt a novel thread inwards Java.