1

I need to execute tasks sequentially:

Executor executor = Executors.newSingleThreadExecutor();

public void push(Runnable task) {
   executor.execute(task);
}

Sometimes a task never ends. I would like to set a timeout to prevent it from blocking the next.

Edit: I need a "fire and forget" design as I can't block the caller of this execution

Philippe Blayo
  • 10,610
  • 14
  • 48
  • 65
  • 1
    Take a look at [ExecutorService that interrupts tasks after a timeout](http://stackoverflow.com/questions/2758612/executorservice-that-interrupts-tasks-after-a-timeout) – MadProgrammer Sep 06 '13 at 05:18

1 Answers1

2

This can be done using Future object.

ExecutorService executor = Executors.newSingleThreadExecutor();

    Runnable task = new Runnable() {
        @Override
        public void run() {
            //do your task
        }
    };

    Future<?> future = executor.submit(task);

    future.get(60, TimeUnit.SECONDS); // awaits termination