Search code examples
javamultithreadingparallel-processingcompletable-futurecallable

How to run multiple methods parallely and get outputs from each of them in java


I want to run three different methods in parallel to improve the performance in Java. Also I need to get the outputs from all the three of them. Below is the sample which I have tried. here, I'm not sure how to retrieve the returned string values. Please help me to add(concatenate all the three strings to total).

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class test {

    public static void main(String[] args) {
        String total = "";

        Callable<String> callable1 = new Callable<String>()
        {
            @Override
            public String call() throws Exception
            {
                String t1 = "";
                t1 = method1();
                return t1;
            }
        };

        Callable<String> callable2 = new Callable<String>()
        {
            @Override
            public String call() throws Exception
            {
                String t2 = method2();
                return t2;
            }
        };

        Callable<String> callable3 = new Callable<String>()
        {
            @Override
            public String call() throws Exception
            {
                String t3 = method3();
                return t3;
            }
        };

        List<Callable<String>> taskList = new ArrayList<Callable<String>>();
        taskList.add(callable1);
        taskList.add(callable2);
        taskList.add(callable3);

        ExecutorService executor = Executors.newFixedThreadPool(3);

        try
        {
            executor.invokeAll(taskList);
            //total = ;(want to concatenate all the strings here).

            System.out.println(total);
        }
        catch (InterruptedException ie)
        {
            //do something if you care about interruption;
        }

    }
    public static String method1()
    {
        System.out.println("method1");
        return "1";

    }

    private static String method2()
    {
        System.out.println("method2");
        return "2";
    }

    private static String method3()
    {
        System.out.println("method3");
        return "3";
    }


}


Solution

  • As taskList is a List<Callable<String>>, executor.invokeAll(taskList) returns a List<Future<String>> containing a Future<String> corresponding to each task in taskList. You need to save that List<Future<String>> so that you can later get at the results of your tasks. Something like this:

    List<Future<String>> futureList = executor.invokeAll(tasklist);
    String result = futureList.get(0).get() +
                    futureList.get(1).get() +
                    futureList.get(2).get();
    

    In addition to InterruptedException, Future.get() can also throw CancellationException and ExecutionException so you need to be prepared to deal with these in your try block.