Re: [Beanshell-dev] Re: Aborting Interpretting

Patrick Niemeyer <[email protected]> Mon, 14 Feb 2005 13:27:50 -0600
Newsgroups gmane.comp.java.beanshell.user,gmane.comp.java.beanshell.devel
Message-ID <[email protected]>
On Feb 14, 2005, at 1:10 PM, Alexey Zinger wrote:

> Pat, my knee jerk reaction to having to stop a thread is to use
> Thread.interrupt() method:
> http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ 
> Thread.html#interrupt()
> Seems to do the right thing and it's not deprecated.  But I haven't  
> tried it
> myself.  It's been a while since I needed to halt a thread and I did  
> use
> Thread.stop() back then as it wasn't deprecated.

Thread interrupt() requires some cooperation from the application that  
is receiving the interrupt.  Interrupts only generate an exception when  
the code is in a blocking I/O or sleep operation...  and the rest of  
the time time the application has to explicitly check for the interrupt  
condition flag.  It's also possible to simply ignore the interrupt and  
go about your business.

BeanShell doesn't currently pay any special attention to the interrupt  
flag so this won't help now.  But it is likely the best way for us to  
implement the job control in the enhancement.  We can do this simply by  
adding checkpoints in the main loop and control structures of  
BeanShell.  While we can never guarantee that user code that BeanShell  
invokes will do the same, but at least then our scripts will do the  
right thing when they have control.  (See various previous threads on  
this topic).

Here is a simple test case.  You can see that interrupt() alone will  
not stop the evaluation.  But changing that call to stop() will work.

import bsh.*;

public class TestStop implements Runnable
{
     public void run() {
         Interpreter i = new Interpreter();
         try {
             i.eval( "while( true ) { print(\"hello\"); }" );
         } catch ( EvalError e ) { System.out.println(e ); }
     }

     public static void main( String [] args ) throws Exception
     {
         Thread t = new Thread( new TestStop() );
         t.start();
         Thread.sleep(2000);
         t.interrupt();
         System.out.println("main done");
     }
}


Pat



-------------------------------------------------------
SF email is sponsored by - The IT Product Guide
Read honest & candid reviews on hundreds of IT Products from real users.
Discover which products truly live up to the hype. Start reading now.
http://ads.osdn.com/?ad_id=6595&alloc_id=14396&op=click