29.7.13

Java apoptosis object; cascading abortion

Instantiating this object will cause cascading interrupts for all threads (including gui threads etc). It is useful for aborting a multi-threaded simulation from within a catch or something. Be aware, calling new Apoptosis() will end the current thread too, so you can never do anything with the object.
 // finds all the threads and kills them  
 public class Apoptosis   
 {  
      // finds all the threads and kills them  
      public Apoptosis()  
      {  
           ThreadGroup allThreads = Thread.currentThread().getThreadGroup();  
           ThreadGroup parentGroup;  
           while ( ( parentGroup = allThreads.getParent() ) != null )   
           {  
                allThreads = parentGroup;  
           }  
           allThreads.interrupt();  
      }  
 }  

Labels: ,

1 Comments:

Anonymous Anonymous said...

My most stupid work memory is when I wrote a Java class that had a failure path that required it to basically exit 1. Due to a policy change at work, we needed 80% unit test coverage. It is stupidly difficult to unit test something that exits, because it's no longer there, so the unit test throws a fit. So I managed to completely re-write it so that I could mock out the System.exit() call and then check that it was called.

My code was a mess, but hey, 80%+ unit test coverage.

11/23/2024 10:57 pm  

Post a Comment

Subscribe to Post Comments [Atom]

<< Home