Search code examples
javaandroidexecutorservicerunnablecompletable-future

Delayed ExecutorService with manual start


I have a simple ExecutorService (via Executors.newSingleThreadExecutor()) that I use to submit Runnables to. However, I would like to queue up these Runnables and only let the ExecutorService execute them once I manually notify it (only once).

N.B. I am not trying to make this into a synchronous procedure -- I merely want to control when the execution of the submitted Runnables


Solution

  • Since you tagged your question with , I suppose, you are thinking into the following direction:

    ExecutorService es = Executors.newSingleThreadExecutor();
    
    CompletableFuture<Void> trigger = new CompletableFuture<>();
    
    // submit your jobs
    trigger.thenRunAsync(aRunnable, es);
    trigger.thenRunAsync(anotherRunnable, es);
    trigger.thenRunAsync(yetAnotherRunnable, es);
    
    // and later-on
    trigger.complete(null);
    // now all Runnables will get submitted and executed
    
    
    // you can use the same construct even after trigger point
    // then, the runnable will get submitted immediately
    
    trigger.thenRunAsync(aRunnable, es);
    
    // finally
    es.shutdown();
    

    But note that this will not maintain the submission order as all actions were modeled as only depending on the trigger. If you need to keep the order, you may use something like

    CompletableFuture<Void> trigger = new CompletableFuture<>();
    CompletableFuture<Void> order = trigger;
    
    // submit your jobs
    order = order.thenRunAsync(aRunnable, es);
    order = order.thenRunAsync(anotherRunnable, es);
    order = order.thenRunAsync(yetAnotherRunnable, es);
    
    // and later-on
    trigger.complete(null);
    

    Since this will submit the next job only when the previous has been completed you have to be careful regarding the time of shutting down the ExecutorService. But you can use order.join() to wait for the completion of all jobs.

    Further, care must be taken when different threads may submit jobs this way, as then, the update of the order variable must be done in a threadsafe manner.