Reputation: 173
I know that Thread.sleep(1000);
can be used to freeze the current thread (for 1 second in the example), but since you need to throw an Exception
I am wondering if it is safe to use it. I don't want to use it in a program and accidentally cause problems.
Is it "ok" to use Thread.sleep();
or is there a better way to achieve the same outcome?
Upvotes: 3
Views: 6830
Reputation: 31
Since thread.sleep
Suspends the current thread for a specified time (not kill it). So it's safe to use it.
Upvotes: 0
Reputation: 328735
since you need to throw an Exception I am wondering if it is safe to use it.
Thread#sleep only throws 2 exceptions:
IllegalArgumentException
if the parameter is negativeInterruptedException
if the thread gets interrupted=> if you pass a positive number and the thread doesn't get interrupted there will be no exception.
Unless you call theThread.interrupt()
from another thread you will be fine.
EDIT
It seems you want to create a timer - in that case you would make your life much simpler by using the built-in mechanisms:
Runnable r = new Runnable() {
public void run() { runYourTaskHere(); }
};
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(r, 0, 1, TimeUnit.SECONDS);
Upvotes: 6
Reputation: 3699
As an aside, if you want to sleep and know you won't be using interrupts, a handy way to avoid dealing with the InterruptedExceptions is using Guava's Uninterruptibles, eg
Uninterruptibles.sleepUninterruptibly(1000, TimeUnit.MILLISECONDS);
This transparently deals with the InterruptedException if one is thrown in the recommended way (ie resetting the interrupted status) and avoids unsightly try-catch blocks.
Upvotes: 18
Reputation: 10876
It is perfectly safe. InterruptedException has been provided by JVM so that you can handle it if needed ( suppose you want to do something extra when this thread is interrupted)... It actually doesnt mean that something bad has happened.
Upvotes: 0
Reputation: 24336
Depends on what you are trying to do, I have seen Thread.sleep
used and it is usually used to fix a programming mistake, because people think it resolves race conditions. Thread.sleep
has to throw an exception because Java doesn't control the CPU (last I checked), so if the CPU has a bug or even if it doesn't and wakes a thread up early / interrupts it in some way the program (Java) needs a way to terminate itself and propagate a message up the stack. Further this greatly depends on what you mean by "the same outcome"
Upvotes: 1