5

I'm using ScheduledExecutorService for requeuing events back into a message queue after sometime has passed. Now I need that after some event is triggered all the scheduled pending tasks of this executor are executed.

I have seen that it is possible to cancel the pending tasks, but I need to run all of them before the executor is closed. Is there a way to do this? Or should I use a different strategy to schedule this tasks.

Carlos Andres
  • 417
  • 4
  • 13

2 Answers2

2

Or should I use a different strategy to schedule this tasks.

Yes, you should use another strategy.

As the same suggests, a ScheduledExecutorService is for scheduling to run a task after a certain amount of time has passed. If you do not know when a task

If you want to buffer some tasks to be executed at a later undetermined time, collect your Runnable or Callable objects as you would any other bunch of objects. Use a class from the Java Collections framework.

If you care about the tasks being run in a particular order, such as LIFO or FIFO, use a Queue or Deque implementation.

When the time arrives to run your tasks, feed the Runnable/Callable objects from the queue/deque and submit to an executor service.

  • If you care about the tasks running serially, and not overlapping their executions in time, then use a single-threaded executor service.
    • ExecutorService es = Executors.newSingleThreadExecutor​() ;
  • If, instead, you care about getting a bunch of tasks done as soon as possible, then you might want to use an executor service backed by a thread pool. This assumes your deployment machine has multiple cores, and/or your your tasks are not CPU-bound (the tasks spend significant time waiting on resources such as network calls, reading/writing to storage drives, database queries, etc.).
    • ExecutorService es = Executors.newCachedThreadPool() ;
    • ExecutorService es = Executors.newFixedThreadPool​( 4 ) ;

Obligatory tip: Read, re-read, and study the superb book, Java Concurrency in Practice by Brian Goetz, et al.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
2

ExecutorService::shutdownNow

The object ScheduledExecutorService has a method: shutdownNow(). It will return a List<Runnable> that can be executed.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Carlos Andres
  • 417
  • 4
  • 13
  • 1
    Caution: Some implementations of that method will interrupt the currently executing task(s), with their work left undone. Read the Javadoc carefully. I do not believe this achieves the goal of the Question. – Basil Bourque May 17 '20 at 18:49
  • I'll have that into account. Thanks! – Carlos Andres May 18 '20 at 17:23