Search code examples
javamultithreadingexecutorserviceexecutor

Add executors dynamically based on a condition in java


If StrTemp.equals(true), I want code as below (I have 2 threads here):

ExecutorService executor = Executors.newFixedThreadPool(2);

Future<String> f1 = executor.submit(new Callable<String >() {
    public String  call() throws Exception {
        return dao.getS4PricingResponse(pricingRequestTemp);
    }
});
Future<String> f2 = executor.submit(new Callable<String>() {
    public String call() throws Exception {
        return dao.getS4ProductResponse(productRequestTemp);
    }
});

If it's not true I want three threads to be created. I will add one more f3=executor.submit. How can I decide this dynamically and make it more efficient?


Solution

  • You are mixing up two things that don't belong together.

    • the executor service and its tasks: that service doesn't know or care about how many threads will be there to run tasks. In other words: just submit your work items into it.
    • but you have to "fix" the number of threads upfront, and the simple solution would look

    like this:

    int numThreads = (whateverStrTemp.equals(somethingElse)) ? 2 : 3;
    ExecutorService executor = Executors.newFixedThreadPool(numThreads);
    // now submit all the tasks you want to submit ...
    

    Regarding the comment: that one isn't easily possible. The method calls differ in two aspects: the method that gets called and the parameter that gets passed! You could put lambdas for the different calls into a map, but you would probably need another map that holds a lambda that fetches the parameter to pass to the first lambda. From that point of view, I don't see a reasonable way to refactor just this code.

    I would step back, and look at the underlying problem you try to solve, and look into ways of designing that differently, to get to a better solution.

    Beyond that, you could put all that code into a single loop, and add the futures to a List<Future<String>> instead of creating variables f1, f2, ... (hint: whenever you start using names like foo1, foo2, ... you should stop immediately and use an array or list).