Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@aakoch
Created August 28, 2018 01:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aakoch/492d27df9034a05df853c2d44ced904d to your computer and use it in GitHub Desktop.
Save aakoch/492d27df9034a05df853c2d44ced904d to your computer and use it in GitHub Desktop.
Demonstration of the correct way to handle InterruptedException
/**
* 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