I've been reading around about InterruptedException, and it's immediately apparent that there's no silver bullet solution to handle it properly in all cases.
What I haven't seen yet, is some sample code demonstrating what can go wrong if the exception is handled improperly. Of course I realize some of the effects (such as thread starvation, which I think is one of them) are hard to demonstrate. I want to keep it limited to demonstrating the proper use of Thread.sleep()
.
How would you go about designing a somewhat realistic sample program for this?
Here are my ideas so far:
Make a simple GUI application to demonstrate reduced responsiveness. There'd be a UI thread, and a simple thread pool to perform some blocking task. The thread pool manager checks the interrupted status of the running threads to manage them. Swallowed
InterruptedException
s cause the pool to run out of threads, so the application becomes less responsive.This can help point out the different handling strategies for when sleeping in a managed thread vs. an unmanaged one.
Have a bunch of threads that create garbage and sleep. There would be two types of threads: ones that restore the interrupted status when interrupted, and those that don't (swallow the exception). Then the demonstration would be to run the application in a JVM with little memory, and (hopefully) show that swallowing the exception somehow inhibits garbage collection or increases its overhead (due to long interval between invocations).
Do these ideas make sense? Any other (maybe simpler) ideas?
Say you have a Thread which you want to be able to shutdown by interrupting it.
By discarding the interrupt, you can have a thread which sometimes fails to die causing a resource leak you cannot fix without restarting the application.
Ignoring any exception is a very bad idea 95+% of the time. This is why they are checked exceptions in Java. These problems are not limited to interrupts.