在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);
}
答案 0 :(得分:0)
除非另有证明,否则这似乎是由于不良的设计/实施。