为什么ExecutorService.submit在ExecutionException中包装错误?

时间:2018-02-18 08:24:49

标签: java

Error中包含非java.util.concurrent.ExecutionException个例外是有意义的,但为什么错误(例如OutOfMemoryError)也包含在ExecutionException内?抛弃Errors而不将它们包裹在ExecutionException内会更有意义吗?

以下示例代码演示了如果您使用-Xmx32m运行它:

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        final ExecutorService executor = Executors.newSingleThreadExecutor();
        final Runnable memoryEater = () -> {
            final ArrayList<String> fatList = new ArrayList<>();

            for (long i = 0; i < Long.MAX_VALUE; i++) {
                for (long j = 0; j < i; j++) {
                    fatList.add(String.valueOf(i));
                }
            }

            System.out.println(fatList.size());
        };

        executor.submit(memoryEater).get();
    }

}

逻辑在java.util.concurrent.FutureTask#report内:

/**
 * Returns result or throws exception for completed task.
 *
 * @param s completed state value
 */
@SuppressWarnings("unchecked")
private V report(int s) throws ExecutionException {
    Object x = outcome;
    if (s == NORMAL)
        return (V)x;
    if (s >= CANCELLED)
        throw new CancellationException();
    throw new ExecutionException((Throwable)x);
}

1 个答案:

答案 0 :(得分:0)

除非另有证明,否则这似乎是由于不良的设计/实施。