Background: I’ve been habitually converting Thread.sleep() calls to TimeUnit.XXX.sleep() calls, whenever I need to otherwise touch code containing that.
Questions: First of all, is this ok, or is there some subtle problem with TimeUnit’s sleep? Then, as far as I’ve figured out, this is best way to wait before a network (or similar) operation retry like
for(int retriesLeft = 3; ;--retriesleft) {
try {
doOperation(...);
break;
} catch (IOException ex) {
if (retryCountDown <= 0) throw ex;
else TimeUnit.SECONDS.sleep(10);
}
}
Is TimeUnit.XXXX.sleep(10) the right way to sleep above, or is there a better way? Also, feel free to comment if there’s a better Java pattern to handle the whole network operation retry logic…
Thread.sleep() only accepts time in milliseconds.Therefore a helper class was introduced TimeUnit which would specify the units like SEC, HOURs which is much more convenient thn inputting milliseconds. It helps in increasing the readability of the code also.
check the javadoc: http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/TimeUnit.html