Search code examples
javamultithreadingconcurrencyexecutorservicejava.util.concurrent

Dynamically submitting tasks to ExecutorService based on condition


I am currently using ExecutorServices with fixed thread pool and submitting 3 tasks.

ExecutorService executorService = Executors.newFixedThreadPool(3);

Future<Object1> = executorService.submit(task1);

Future<Object2> = executorService.submit(task2);

Future<Object3> = executorService.submit(task3);

executorService.shutdown();

executorService.awaitTermination(10000, TimeUnit.MILLISECONDS)

Now this works perfectly as i always had the requirement to execute all these differences 3 services, but now i want to customize it. For instance i may just need to run service 1, service 2, service 3 or any combination of them or all of them.

How can i customize which all services I want to submit for exectution and the thread pool size ?

I am not interested in doing creepy if checks around to check if service 1 required etc.


Solution

  • What I'm thinking you'll want to do is abstract out your access to the ExecutorService and pass in the tasks you want it to work on dynamically.

    Note that I'm not making any guarantees or promises of performance here; this is the concept one would want to think along the lines of at least.

    Provided that I am sure that I want to tear down the thread pool every time, I can dynamically set the size of the thread pool to the size of the tasks passed in.

    public void executeTasks(Callable<?>... tasks) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(tasks.length);
        for(Callable<?> task : tasks) {
            executorService.submit(task);
        }
    
        executorService.shutdown();
        executorService.awaitTermination(10000, TimeUnit.MILLISECONDS);
    }
    

    Provided you handle the InterruptedException, you could invoke it thus:

    obj.executeTaks(future1, future3);