Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interrupted exception vs isInterrupted in a while loop

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?

like image 629
Jim Avatar asked Oct 15 '25 12:10

Jim


1 Answers

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.

like image 138
Jean Logeart Avatar answered Oct 17 '25 02:10

Jean Logeart