[concurrency-interest] ExecutorCompletionService for scheduledtask

Outside - Karl's ACM kpauls at acm.org
Tue Aug 15 16:28:37 EDT 2006


Hanson,

Since you're not concerned about the Future's results; that looks great. It
also helps that there will only ever be one TimeoutException thrown within
your loop.

-karl


> Below is the "simplest" or most "lightweight" code fragment I can
> think of to cancel all tasks (that have been scheduled to run after M
> seconds delay) if not all completed within a total of N seconds (where
> N > M).  Please shout if you spot any weakness/drawback.
> 
> Hanson
> 
> ...
>         List<ScheduledFuture> scheduledFutureList = ...// scheduled to
> run after M seconds delay
> 
>         // Let's wait for a maximum of N seconds.
>         // We will exit regardless even if not all open sessions have
> been closed.
>         final long dueTimeMillis = System.currentTimeMillis() + N * 1000;
>         boolean interrupted = false;
> 
>         for (ScheduledFuture scheduledFuture : scheduledFutureList)
>         {
>             long timeoutMillis = dueTimeMillis -
> System.currentTimeMillis();
> 
>             if (timeoutMillis <= 0)
>             {
>                 scheduledFuture.cancel(true);
>                 continue;
>             }
>             try {
>                 scheduledFuture.get(timeoutMillis, TimeUnit.MILLISECONDS);
>             } catch (ExecutionException e) {
>                // log it or whatever
>             } catch (TimeoutException e) {
>                // log it or whatever
>             } catch (InterruptedException e) {
>                // log it or whatever
>                 interrupted = true;
>             } finally {
>                 scheduledFuture.cancel(true);
>             }
>         }
> 
>         if (interrupted)
>             Thread.currentThread().interrupt();
> 
> ...



More information about the Concurrency-interest mailing list