When does Java's Thread.sleep throw InterruptedException? Is it safe to ignore it? I am not doing any multithreading. I just want to wait for a few seconds before retrying some operation.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Methods like
sleep()
andwait()
of classThread
might throw anInterruptedException
. This will happen if some otherthread
wanted to interrupt thethread
that is waiting or sleeping.A solid and easy way to handle it in single threaded code would be to catch it and retrow it in a RuntimeException, to avoid the need to declare it for every method.
The Java Specialists newsletter (which I can unreservedly recommend) had an interesting article on this, and how to handle the
InterruptedException
. It's well worth reading and digesting.The
InterruptedException
is usually thrown when a sleep is interrupted.You should generally NOT ignore the exception. Take a look at the following paper:
See the entire paper here:
http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html?ca=drs-
If an
InterruptedException
is thrown it means that something wants to interrupt (usually terminate) that thread. This is triggered by a call to the threadsinterrupt()
method. The wait method detects that and throws anInterruptedException
so the catch code can handle the request for termination immediately and does not have to wait till the specified time is up.If you use it in a single-threaded app (and also in some multi-threaded apps), that exception will never be triggered. Ignoring it by having an empty catch clause I would not recommend. The throwing of the
InterruptedException
clears the interrupted state of the thread, so if not handled properly that info gets lost. Therefore I would propose to run:Which sets that state again. After that, finish execution. This would be correct behaviour, even tough never used.
What might be better is to add this:
...statement to the catch block. That basically means that it must never happen. So if the code is re-used in an environment where it might happen it will complain about it.