I get exception when using Thread.sleep(x) or wait()
You have a lot of reading ahead of you. From compiler errors through exception handling, threading and thread interruptions. But this will do what you want:
try {
Thread.sleep(1000); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
Exception Handling in case of Thread.sleep and wait() method in case of Threads
I was wondering how to handle the interrupted Exception that is thrown by Thread.sleep method and the Object Class's wait method
There are two important things to realize about InterruptedException
. First off, when it is thrown the interrupt flag on the Thread
is cleared. So you should always do something like:
} catch (InterruptedException e) {
// re-add back in the interrupt bit
Thread.currentThread().interrupt();
...
}
This is a very important pattern because it allows other code that might be calling yours to detect the interrupt as well.
Secondly, in terms of threads, if they are interrupted, they should most likely cleanup and quit. This is certainly up to you, the programmer, but the general behavior is to terminate and quit the operation being performed – often because the program is trying to shutdown.
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
// we are being interrupted so we should stop running
return;
}
Lastly, with any exception handling, the default Eclipse template is usually the wrong thing to do. Never just e.printStackTrace();
the exception. Figure out what you want to do with it: re-throw it as another exception, log it somewhere better, or exit the thread/method/application.
is Thread.sleep() guaranteed to wait?
I am not sure if I will run into trouble with my host machine's thread scheduler
No, the runtime will not interrupt an application thread for any reason. Only other code in your application (or code that you drag in with some framework that you choose) will interrupt threads.
Every task should specify an interruption policy: what will happen if the thread is interrupted? An application should never interrupt a thread without understanding its interrupt policy and being prepared to deal with the consequences.
So, define the interrupt policy for your thread. In your application, it is something you don't expect to happen, and if someone adds code to your application that calls interrupt()
on your thread, they introduced a bug. Basically, your policy is that interruption isn't allowed. So, throwing a some unchecked exception, like IllegalStateException
is a valid response.
Is this the proper way of implementing this behaviour?
No, it's not. When you are interrupted, you should signal callers that you were interrupted. This should be done by letting an InterruptedException
propagate back to the caller (or a application-defined exception with similar meaning), or by restoring the interrupt status on the current thread. Suppose your interruption policy permits interruption, by terminating the loop prematurely. You should still restore the interrupt status:
while(true) {
...
try {
Thread.sleep(10000);
} catch(InterruptedException abort) {
Thread.currentThread().interrupt();
break;
}
/* Make web service call here... */
}
How do I fix a compilation error for unhandled exception on call to Thread.sleep()?
Thread.sleep can throw an InterruptedException which is a checked exception. All checked exceptions must either be caught and handled or else you must declare that your method can throw it. You need to do this whether or not the exception actually will be thrown. Not declaring a checked exception that your method can throw is a compile error.
You either need to catch it:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
// handle the exception...
// For example consider calling Thread.currentThread().interrupt(); here.
}
Or declare that your method can throw an InterruptedException
:
public static void main(String[]args) throws InterruptedException
Related
- Lesson - Exceptions
- When does Java's Thread.sleep throw InterruptedException?
- Java theory and practice: Dealing with InterruptedException
Using Object.wait instead of Thread.sleep for time-synchronization
Because they did it wrong.
There is no reason to implement that 5 second sleeping using Object.wait
. Object.wait
is used for synchronization and Thread.sleep
for sleeping.
Synchronizing on this
is another hint that it all is bad programming. You should avoid it in general unless you have a really good reason for it and in such case it should be documented, which is not the case.
Furthermore when I follow your link I see it this way in their page :
/**
* The IntentService calls this method from the default worker thread with
* the intent that started the service. When this method returns, IntentService
* stops the service, as appropriate.
*/
@Override
protected void onHandleIntent(Intent intent) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// Restore interrupt status.
Thread.currentThread().interrupt();
}
}
}
So maybe they have realized of their mistake and corrected it.
Take notice of how in that code interrupts are properly handled rather than discarded as in the two pieces of code in the original question.
Difference between wait() vs sleep() in Java
A wait
can be "woken up" by another thread calling notify
on the monitor which is being waited on whereas a sleep
cannot. Also a wait
(and notify
) must happen in a block synchronized
on the monitor object whereas sleep
does not:
Object mon = ...;
synchronized (mon) {
mon.wait();
}
At this point the currently executing thread waits and releases the monitor. Another thread may do
synchronized (mon) { mon.notify(); }
(on the same mon
object) and the first thread (assuming it is the only thread waiting on the monitor) will wake up.
You can also call notifyAll
if more than one thread is waiting on the monitor – this will wake all of them up. However, only one of the threads will be able to grab the monitor (remember that the wait
is in a synchronized
block) and carry on – the others will then be blocked until they can acquire the monitor's lock.
Another point is that you call wait
on Object
itself (i.e. you wait on an object's monitor) whereas you call sleep
on Thread
.
Yet another point is that you can get spurious wakeups from wait
(i.e. the thread which is waiting resumes for no apparent reason). You should always wait
whilst spinning on some condition as follows:
synchronized {
while (!condition) { mon.wait(); }
}
When InterruptedException thrown from Thread.sleep?
As I know, InterruptedException is generated when you try to kill/interrupt the thread that is sleeping.
Thread.sleep() isn't pausing execution
Are you sure the code inside the if is being run? The condition on the while is different (+toLowerCase). Thread.sleep()
always causes the current thread to sleep.
Related Topics
Data Access Object (Dao) in Java
Java - Get a List of All Classes Loaded in the Jvm
Io Error: the Network Adapter Could Not Establish the Connection
How to Have Explained the Difference Between an Interface and an Abstract Class
How to Create Custom Methods for Use in Spring Security Expression Language Annotations
Using Generics in Spring Data JPA Repositories
Swingutilities.Invokelater() Why Is It Needed
How to Draw the Same Moving Image Multiple Times
Comparing Two Java.Util.Dates to See If They Are in the Same Day
Move/Copy File Operations in Java
Why Dec 31 2010 Returns 1 as Week of Year
What Is the Maven-Shade-Plugin Used For, and Why Would You Want to Relocate Java Packages
Likelihood of Collision Using Most Significant Bits of a Uuid in Java
Why Doesn't Java Allow to Throw a Checked Exception from Static Initialization Block