简体   繁体   中英

What's a good sample program to demonstrate improper handling of InterruptedException thrown by Thread.sleep()?

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:

  1. 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.

  2. 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.

public void run() {
   while(!Thread.currentThread().interrupted()) {
       doWork();     
       callMethodWhichIgnoresInterrupted();
   }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM