Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>How about:</p> <p>Submit your <code>Callable</code> to the <code>ExecutorService</code> and keep a handle to the returned <code>Future</code>.</p> <pre><code>ExecutorService executorService = ... // Create ExecutorService. Callable&lt;Result&gt; callable = new MyCallable(); // Create work to be done. Future&lt;Result&gt; fut = executorService.submit(callable); </code></pre> <p>Wrap the <code>Future</code> in an implementation of <code>Delayed</code> whereby <code>Delayed</code>'s <code>getDelay(TimeUnit)</code> method returns the maximum execution time for the work in question.</p> <pre><code>public class DelayedImpl&lt;T&gt; implements Delayed { private final long maxExecTimeMillis; private final Future&lt;T&gt; future; public DelayedImpl(long maxExecTimeMillis, Future&lt;T&gt; future) { this.maxExecMillis = maxExecMillis; this.future = future; } public TimeUnit getDelay(TimeUnit timeUnit) { return timeUnit.convert(maxExecTimeMillis, TimeUnit.MILLISECONDS); } public Future&lt;T&gt; getFuture() { return future; } } DelayedImpl impl = new DelayedImpl(3000L, fut); // Max exec. time == 3000ms. Add the `DelayedImpl` to a `DelayQueue`. Queue&lt;DelayedImpl&gt; queue = new DelayQueue&lt;DelayImpl&gt;(); queue.add(impl); </code></pre> <p>Have a thread repeatedly <code>take()</code> from the queue and check whether each <code>DelayedImpl</code>'s <code>Future</code> is complete by calling <code>isDone()</code>; If not then cancel the task.</p> <pre><code>new Thread(new Runnable() { public void run() { while (!Thread.interrupted) { DelayedImpl impl = queue.take(); // Perform blocking take. if (!impl.getFuture().isDone()) { impl.getFuture().cancel(true); } } } }).start(); </code></pre> <p>The main advantage to this approach is that you can set a <strong>different maximum execution time per task</strong> and the delay queue will automatically return the task with the smallest amount of execution time remaining.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload