Created
August 28, 2018 01:06
-
-
Save aakoch/492d27df9034a05df853c2d44ced904d to your computer and use it in GitHub Desktop.
Demonstration of the correct way to handle InterruptedException
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Demonstrates correct (and incorrect) usage of catching InterruptedException. | |
* | |
* @author aakoch | |
*/ | |
public class InterruptedExceptionDemo | |
{ | |
public static void main(String[] args) throws InterruptedException | |
{ | |
Thread t = correctHandling(); | |
t.start(); | |
Thread.sleep(1100); | |
t.interrupt(); | |
t = incorrectHandling(); | |
t.start(); | |
Thread.sleep(1100); | |
t.interrupt(); | |
} | |
private static Thread correctHandling() | |
{ | |
Thread t = new Thread(new Runnable() | |
{ | |
@Override public void run() | |
{ | |
// check if the thread has been interrupted | |
while (!Thread.interrupted()) | |
{ | |
System.out.print('.'); | |
try | |
{ | |
Thread.sleep(500); | |
} | |
catch (InterruptedException e) | |
{ | |
System.err.println("caught interrupted exception"); | |
e.printStackTrace(); | |
// make sure to reset the interrupted flag | |
Thread.currentThread().interrupt(); | |
} | |
} | |
} | |
}); | |
return t; | |
} | |
private static Thread incorrectHandling() | |
{ | |
Thread t = new Thread(new Runnable() | |
{ | |
@Override public void run() | |
{ | |
while (!Thread.interrupted()) | |
{ | |
System.out.print('.'); | |
try | |
{ | |
Thread.sleep(500); | |
} | |
catch (InterruptedException e) | |
{ | |
System.err.println("caught interrupted exception"); | |
e.printStackTrace(); | |
// incorrect *not* to reset the interrupt status | |
// Thread.currentThread().interrupt(); | |
} | |
} | |
} | |
}); | |
return t; | |
} | |
private static Thread incorrectHandling2() | |
{ | |
Thread t = new Thread(new Runnable() | |
{ | |
@Override public void run() | |
{ | |
// incorrect *not* to check if the thread was interrupted | |
while (true) | |
{ | |
System.out.print('.'); | |
try | |
{ | |
Thread.sleep(500); | |
} | |
catch (InterruptedException e) | |
{ | |
System.err.println("caught interrupted exception"); | |
e.printStackTrace(); | |
Thread.currentThread().interrupt(); | |
} | |
} | |
} | |
}); | |
return t; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment