What is a good sample program to demonstrate the incorrect handling of InterruptedException thrown by Thread.sleep ()?

I read about InterruptedException, and it’s immediately obvious that there is no solution with a silver bullet to handle it correctly in all cases.

What I haven't seen yet is a sample code demonstrating what might go wrong if an exception is handled improperly. Of course, I understand that some of the effects (like thread puzzles, which, in my opinion, are one of them) are hard to demonstrate. I want to limit this to demonstrate proper use Thread.sleep().

How would you like to design a somewhat realistic program for this?

Here are my ideas:

  • Make a simple graphical application to demonstrate reduced responsiveness. There will be a UI thread and a simple thread pool to perform some kind of locking task. The thread pool manager checks the interrupted status of running threads to manage them. Swallowing InterruptedExceptioncauses the pool to work from threads, so the application becomes less responsive.

    This can help indicate different sleep strategies in managed flow and unmanaged.

  • Have a bunch of streams that create junk and sleep. . There would be two types of threads: those that restore the interrupted status upon interruption, and those that do not (swallow the exception). Then the demonstration will be to run the application in the JVM with little memory and (hopefully) show that swallowing the exception somehow blocks garbage collection or increases its overhead (due to the long interval between calls).

Do these ideas make sense? Any other (possibly simpler) ideas?

+3
source share
1 answer

Say you have a Thread that you want to disable by aborting it.

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

, , , , .

- 95%% . Java. .

+4

Source: https://habr.com/ru/post/1790645/


All Articles