Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to call sleep and propagate exception

Tags:

java

guava

I want to call Thread.sleep, and to propagate the InterruptException if indeed it's thrown.

Imaginary syntax:

Interruptibles.sleep(1000);

which is equivalent to

try {
    Thread.sleep(1000);
} catch (InterruptException e) {
    throw Throwables.propagate(e);
}

Is there a similar function in a common library (guava, apache commons etc).

like image 347
HBase Avatar asked Dec 15 '22 15:12

HBase


2 Answers

Wrapping in a RuntimeException is likely to cause pain down the line. This is a complicated topic, I recommend the relevant section from Java Concurrency in Practice to fully understand your options.
Guava has sleepUninterruptibly which implements one of the standard idioms described there.

like image 178
Anthony Zana Avatar answered Feb 02 '23 00:02

Anthony Zana


You can do this.

try {
    Thread.sleep(1000);
} catch (InterruptException e) {
    Thread.currentThread().interrupt();
}

or

try {
    Thread.sleep(1000);
} catch (InterruptException e) {
    Thread.currentThread().stop(e);
}

but it usually best to let the exception "bubble up" to somewhere you can handle it correctly. Your IDE can make this easy by filling in the code you need for you.

like image 34
Peter Lawrey Avatar answered Feb 01 '23 22:02

Peter Lawrey