Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use return value from ExecutorService

Tags:

java

I am running a for loop under ExecutorService (which sends emails)

If any of the return type is fail , i need to return return resposne as "Fail" or else i need to return return resposne as "Success"

But i couldn't able to return value in this case

I tried as this way

import java.text.ParseException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {
    public static void main(String[] args) throws ParseException {
    String response =   getDataCal();
    System.out.println(response);
    }
    public static String getDataCal() {
        ExecutorService emailExecutor = Executors.newSingleThreadExecutor();
        emailExecutor.execute(new Runnable() {


            @Override
            public void run() {
                try {

                    for(int i=0;i<2;i++)
                    {

                    String sss = getMYInfo(i);
                    System.out.println();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        });
        return sss;
    }

    public static String getMYInfo(int i)
    {
        String somevav = "success";//Sometimes it returns fail or success
        if(i==0)
        {
            somevav ="success";
        }
        else
        {
            somevav ="fail";
        }

        return somevav;
    }

}
like image 374
Pawan Avatar asked Feb 16 '17 14:02

Pawan


1 Answers

Call your getMYInfo(i) in Callable<String>, submit this callable to executor, then wait for competition of Future<String>.

private static ExecutorService emailExecutor = Executors.newSingleThreadExecutor();

public static void main(String[] args) {
    getData();
}

private static void getData() {
    List<Future<String>> futures = new ArrayList<>();
    for (int i = 0; i < 2; i++) {
        final Future<String> future = emailExecutor.submit(new MyInfoCallable(i));
        futures.add(future);
    }
    for (Future<String> f : futures) {
        try {
            System.out.println(f.get());
        } catch (InterruptedException | ExecutionException ex) {
        }
    }
}

public static String getMYInfo(int i) {
    String somevav = "success";
    if (i == 0) {
        somevav = "success";
    } else {
        somevav = "fail";
    }
    return somevav;
}

private static class MyInfoCallable implements Callable<String> {

    int i;

    public MyInfoCallable(int i) {
        this.i = i;
    }

    @Override
    public String call() throws Exception {
        return getMYInfo(i);
    }

}
like image 122
MBec Avatar answered Oct 11 '22 03:10

MBec