Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java executor framework's invokeAll equivalent method in spring executor

In java executor framework to wait until completion of all tasks we have invokeAll() method .But while using spring's ThreadPoolTaskExecutor we have only submit method which returns Future object.So here after completion of first task it is going to be started next task.So If I want to wait until all tasks completed is there any way to do it? means is there any method available in spring which is equal to invokeAll() Please correct me if my understanding is wrong..

like image 524
PSR Avatar asked Oct 24 '25 05:10

PSR


2 Answers

You can wrap your TaskExecutor with org.springframework.core.task.support.ExecutorServiceAdapter:

ExecutorServiceAdapter adapter = new ExecutorServiceAdapter(taskExecutor);

List<Future<V>> futures = adapter.invokeAll(tasks);

Hope it helps.

like image 189
eltabo Avatar answered Oct 26 '25 19:10

eltabo


Always fail into ThreadPoolTaskExecutor source code made me stupid. you remind me the whether ExecutorServiceAdapter belongs to spring. Now i think yes, and here is my code to answer your question, hope not wrong.

ThreadPoolTaskExecutor threadPool = atx.getBean("threadPool", ThreadPoolTaskExecutor.class);
    ExecutorServiceAdapter adapter = new ExecutorServiceAdapter(threadPool);
    List<Callable<Integer>> tasks = new ArrayList<>();
    Callable<Integer> task = null;
    for (int i = 0; i < 10; i++){
        task = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int time = new Random().nextInt(1000);
                Thread.sleep(100);
                System.out.println(Thread.currentThread().getName() + " has slept " + time);
                return time;
            }
        };
        //submit task and wait to execute
        threadPool.submit(task);
        //add all task to list
        tasks.add(task);
    }

    //get the start time of all threads
    long start = System.currentTimeMillis();
    try {
        List<Future<Integer>> result = adapter.invokeAll(tasks);
        for (int i = 0; i < result.size(); i++){
            System.out.println(result.get(i).get());
        }
    } catch (ExecutionException ex){
        ex.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("Total time is " + (System.currentTimeMillis() - start));
like image 45
Crabime Avatar answered Oct 26 '25 21:10

Crabime



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!