After I have switched from Java 11 to Java 17 (OpenJDK installed from Ubuntu 20.04 repository), the following code doesn't work:
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.exception.ExceptionUtils;
public class TestClass {
public static void main(String[] args) {
CompletableFuture<String> streamFuture = CompletableFuture.supplyAsync(() -> {
throw MyException.wrapIfNeeded(new Exception("MyException"));
});
String result = null;
try {
result = streamFuture.get();
} catch (Exception e) {
System.out.println("Exception: " + ExceptionUtils.getMessage(e));
}
System.out.println("Result: " + Objects.toString(result));
}
static class MyException extends RuntimeException {
private static final long serialVersionUID = 3349188601484197015L;
public MyException(Throwable cause) {
super(cause == null ? null : cause.getMessage(), cause);
}
public static MyException wrapIfNeeded(Throwable e) {
return e instanceof MyException ? (MyException) e : new MyException(e);
}
@Override
public String toString() {
return ReflectionToStringBuilder.toString(this);
}
}
}
There is a problem in streamFuture.get() - it hangs infinitely. I dug deeper and found that in java.util.concurrent.ForkJoinPool there is a method unmanagedBlock(ManagedBlocker blocker) which looks like
/** ManagedBlock for external threads */
private static void unmanagedBlock(ManagedBlocker blocker)
throws InterruptedException {
if (blocker == null) throw new NullPointerException();
do {} while (!blocker.isReleasable() && !blocker.block());
}
and the program hangs infinitely in the do-while loop.
EDIT:
I found out the problem is cause by the toString() method added to my custom exception class. For some reason it started to be a problem after Java 11