3 ms·
Here's a common pattern for sleeping on a thread you do not expect to be interrupted and both are equally valid and fine ways to implement it: try { Thr
by wellpast 10y ago
Here's a common pattern for sleeping on a thread you do not expect to be interrupted and both are equally valid and fine ways to implement it:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// never happens
}
In other words, the correct handling is to swallow or throw. The former is likely preferred by those who do assertion-based coding. The latter for people that prefer to discover their bugs in other ways.
- coredog64 10y agoOne should never expect a thread not to be interrupted. When I see code like the latter in PRs it drives me nuts, to the point that I start building up a case to have the knucklehead that does it moved off onto another project.
- wellpast 10y agoWhy should one always expect a thread to be interruptible? If I don't run my thread within an Executor or some other framework that could interrupt my thread, then I should be able to consider that an illegal state.
- BrandonM 10y agoWhen a program is shutting down, its threads are interrupted.
- cbsmith 10y agoWell, I agree the correct behaviour is to either swallow or throw, but I'd argue it is more like: try { Thread.sleep(1000); } catch (final InterruptedException e) { //never happens throw new IllegalStateException(e); } or try { Thread.sleep(1000); } catch (final InterruptedException e) { LOG.info("Woken up early", e); }