Interrupted exception vs isInterrupted in a while loop

Jim picture Jim · Feb 19, 2013 · Viewed 10.2k times · Source

Assume that I have the following code:

while(!Thread.currentThread().isInterrupted()){  
    //do something   
    Thread.sleep(5000);  
}

Now Thread.sleep throws `InterruptedException so it should be like this:

while(!Thread.currentThread().isInterrupted()){  
   //do something   
   try{  
     Thread.sleep(5000);    
   } catch(InterruptedException e){  

   }
}

If I hit the catch will the while loop continue or do I need to do Thread.currentThread().interrupt()? If I do call this method, won't that also cause an InterruptedException? Otherwise how I got the exception in the first place?

Also if I have:

while (!Thread.currentThread().isInterrupted()){  
   //do something   
   callMethod();  
}  

private void callMethod(){  
   //do something  
   try {  
     Thread.sleep(5000);    
   } catch(InterruptedException e){  

   }
}

again will my while loop break?

Answer

Jean Logeart picture Jean Logeart · Feb 19, 2013

Actually your question is more about try - catch - finally than about multithreading.

1) If sleep throws an Exception, the catch block will execute and then the while loop continues.

2) You do the exact same thing as in 1)

To leave the while loop, do:

try{  
   while(!Thread.currentThread.isInterrupted){  
       //do something   
       Thread.sleep(5000);    
   }  
}
catch(InterruptedException e){  

}

In that case, if an Exception is thrown, the while loop is left and the catch block is executed.