I was trying to write a Producer Consumer model (Producer thread and Consumer Thread in java)
I was wondering how to handle the InterruptedException that is thrown by Thread.sleep method and the Object Class’s 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 there may not be any need to take care of these exception (My Assumption).
But I wanted to know what could be the different scenarios possible in which we need to handle this exception.
There are two important things to realize about
InterruptedException. First off, when it is thrown the interrupt flag on theThreadis cleared. So you should always do something like:This is a very important pattern because it allows other code that might be calling yours to detect the interrupt as well.
Secondly, in terms of threads, if they are interrupted, they should most likely cleanup and quit. This is certainly up to you, the programmer, but the general behavior is to terminate and quit the operation being performed – often because the program is trying to shutdown.
Lastly, with any exception handling, the default Eclipse template is usually the wrong thing to do. Never just
e.printStackTrace();the exception. Figure out what you want to do with it: re-throw it as another exception, log it somewhere better, or exit the thread/method/application.