Interrupt Handlers
Eric Kolotyluk
eric at kolotyluk.net
Tue Dec 21 00:41:56 UTC 2021
Not for JDK 18 or Project Loom, but while we are thinking about Concurrency
APIs, one thing that has always bugged me is Thread.sleep() because it
looks like
try {
. . .
Thread.sleep(Duration.ofMillis(10))
. . .
}
catch (InterruptedException cause) {
. . .
}
which is too much boilerplate... In my own APIs I do stuff like
public Duration sleep(Consumer<InterruptedException> exceptionHandler) {
final var duration = getDuration();
try {
Thread.sleep(duration);
} catch (InterruptedException interruptedException) {
if (exceptionHandler != null)
exceptionHandler.accept(interruptedException);
}
finally {
return duration;
}
}
so I can write
AtomicInteger value = new AtomicInteger();
var lag = new Lag(minimumDuration, maximumDuration);
Runnable task1 = () -> {
value.set(1);
lag.sleep(cause -> value.set(2));
if (value.get() == 1) value.set(3);
};
Runnable task2 = () -> {
for (int i = 0; i < 10; i++) {
if (Thread.interrupted()) break;
else lag.sleep();
}
};
Maybe not the best example in the world, because it's a unit test, but it
can lead to less boilerplate. I have seen this pattern in other frameworks,
but dealing with StructuredExecturor CompletionHandlers inspired me to use
it in my own APIs. It would be nice to see this pattern adopted in other
Java APIs. For example, I would like to be able to write
Runnable task3 = () -> {
for (int i = 0; i < 10; i++) {
if (Thread.interrupted()) break;
else Thread.sleep(Duration.ofMillis(10), cause -> {});
}
};
Is there an existing JEP where I can make this feature request?
Cheers, Eric
More information about the loom-dev
mailing list