kovacs lorand
kovacs lorand

Reputation: 905

How to catch errors instantly when running multiple threads with executors?

The second thread in my code will throw a divide by 0 exception, but I will only catch it after the first thread finished. The first thread could run for days, so that means that I will only catch my exception after several days that it happened. Can I solve this somehow without subclassing ThreadPoolExecutor and overriding afterExecute?

Here is my code:

    ExecutorService executor = Executors.newCachedThreadPool();

    Future<Integer> future = executor.submit(new MyTestC(4000));
    Future<Integer> future2 = executor.submit(new MyTestC(0));

    ArrayList<Future<Integer>> futures = new ArrayList<>();
    futures.add(future); futures.add(future2);

    for(Future<Integer> f: futures)
    {
        try {
            int result = f.get();
            System.out.println(result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }

class MyTestC implements Callable<Integer> {

int sleep;

public MyTestC(int sleep)
{
    this.sleep = sleep;
}

@Override
public Integer call() throws Exception {
    if(sleep > 0)
        Thread.sleep(sleep);

    //If 0 will throw exception:
    int tmp = 4/sleep;

    return sleep;
}

}

Upvotes: 0

Views: 99

Answers (1)

jtahlborn
jtahlborn

Reputation: 53674

you can use an ExecutorCompletionService to solve this problem. it will return Futures in the order they complete.

Upvotes: 2

Related Questions