Exception handling when using the Thread.sleep and wait () methods in the case of threads

I tried to write a Consumer Producer model (producer stream and Consumer stream in java)

I was wondering how to handle the InterruptedException that is Thread.sleep by the Thread.sleep method and the Object Class wait() method

 package producerconsumer; import java.util.ArrayList; public class Consumer implements Runnable { ArrayList<Integer> container; @Override public void run() { while(true){ System.out.println("Consumer Thread Running"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } if(null==container){ System.out.println("container is null"); } //Removing values from Arraylist synchronized (container) { if(container.size()==0){ try { container.wait(); } catch (InterruptedException e) { //How to tackle this exception e.printStackTrace(); } } Integer removedInteger = container.remove(container.size()-1); System.out.println("removedInteger..."+removedInteger); } } } public void setContainer(ArrayList<Integer> container) { this.container = container; } } 

This is one example I have taken. In this example, it may not be necessary to take care of this exception (My guess).

But I wanted to know what the various scenarios might be in which we need to handle this exception.

+6
source share
1 answer

I was wondering how to handle a thrown exception that is thrown by the Thread.sleep method and the object class wait method

There are two important things to InterruptedException . First of all, when it is reset, the interrupt flag on Thread is cleared. Therefore, you should always do something like:

 } catch (InterruptedException e) { // re-add back in the interrupt bit Thread.currentThread().interrupt(); ... } 

This is a very important pattern, because it allows another code that may call yours to also detect an interrupt.

Secondly, in terms of flows, if they are interrupted, they should most likely clear and exit. This, of course, is up to you, the programmer, but the general behavior is to shut down and exit the operation being performed - often because the program is trying to shut down.

 } catch (InterruptedException e) { Thread.currentThread().interrupt(); // we are being interrupted so we should stop running return; } 

Finally, with any exception handling, the default Eclipse template is usually incorrect. Never just e.printStackTrace(); an exception. Find out what you want to do with it: repeat the throw as another exception, write it somewhere better, or exit the thread / method / application.

+11
source

Source: https://habr.com/ru/post/914134/


All Articles