12

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;
    }

}
Pawan
  • 31,545
  • 102
  • 256
  • 434
  • Please read: http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – walen Feb 16 '17 at 14:30
  • 5
    @walen What? Why? That question is about JS, this one is about Java. – Ordous Feb 16 '17 at 14:34
  • The example is in Javascript, but the explanation in the answer applies to almost any technology. – walen Feb 16 '17 at 14:40
  • 3
    @walen Not really, the OP is asking how to get a return value from an ExecutorService, which does not exist in emcascript. Remeber, Javascript !== Java, Javascript == EmcaScript – Werlious Nov 17 '20 at 02:07
  • @Werlious No, sorry. The OP was asking why they couldn't access the updated value of `sss` right after invoking `execute()` with a callback that updated ir. This shows that, ~4 years ago, OP lacked a clear understanding of how asynchronous calls work. I firmly believe that there's no point in mouth-feeding a solution if the concept behind it is not understood. And the question I linked offers a great **explanation** that could help OP understand how async calls work; an explanation which is basically the same for Java and Javascript (I know because I've been working with both for 10+ years). – walen Nov 17 '20 at 09:41

2 Answers2

19

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);
    }

}
MBec
  • 2,172
  • 1
  • 12
  • 15
  • I would just add the following between the two for loops to make it more correct: emailExecutor.shutdown(); emailExecutor.waitTermination – Muky Jan 20 '20 at 14:27
4

It seems that you want to wait for the completion of the task that you've submitted (why use an ExecutorService?)

You can do that by submitting a Callable<T>, the submit method will then return a Future<T>. You can then get() to wait for completion and obtain the result.

Maurice Perry
  • 9,261
  • 2
  • 12
  • 24
  • "Why use an ExecutorService?" -- potentially this is step towards an eventual program in which some other statements are added between `executor.submit()` and `future.get()`. – slim Feb 16 '17 at 15:02