[concurrency-interest] Advice for execute( Runnable task, long timeout )

Joe Bowbeer jozart at blarg.net
Tue Apr 26 19:56:12 EDT 2005


Jan Nielsen <jnielsen at sungardsct.com> wrote:
> 
> I have a need in JVM 1.3 and above (Solaris, Windows, RedHat, and HPUX) 
> for the following API in dl.util.concurrent.PooledExecutor.execute( 
> Runnable command, long msecs) which interrupts a job if it's not 
> complete after msecs. Snippits are shown below and a modified version 
> PooledExecutor is attached. The implementation seems work but it feels 
> like a hack, in particular the Worker, Work, and Interrupt class 
> interaction seems less than ideal. Is there a better way to implement 
> this in dl.util.concurrent? Any thoughts, suggestions, insights and/or 
> critique are greatly appreciated.
> 

Check out dl.util.concurrent.TimedCallable if you haven't already.

This uses a dedicated thread per Callable, which may be too heavyweight for you, but at least you can execute it on a standard PooledExecutor.

Callable callable = new Callable() {
  public Object call() {
    runnable.run();
    return Boolean.TRUE;
  }
}

callable = new TimedCallable(callable, msecs);

FutureResult future = new FutureResult();
Runnable setter = future.setter(callable);

executor.execute(setter);


I would think something along these lines would also work:

Callable callable = new Callable() {
  public Object call() {
    runnable.run();
    return Boolean.TRUE;
  }
}

FutureResult future = new FutureResult();
Runnable setter = future.setter(callable);

executor.execute(setter);

TimerTask tt = new TimerTask() {
  public void run() {
    future.cancel();
  }
}

timer.schedule(tt, msecs);

Joe.



More information about the Concurrency-interest mailing list