Assume that I have the following code:
while(!Thread.currentThread().isInterrupted()){
//do something
Thread.sleep(5000);
}
Now Thread.sleep throws `InterruptedException so it should be like this:
while(!Thread.currentThread().isInterrupted()){
//do something
try{
Thread.sleep(5000);
} catch(InterruptedException e){
}
}
If I hit the catch will the while loop continue or do I need to do Thread.currentThread().interrupt()? If I do call this method, won't that also cause an InterruptedException? Otherwise how I got the exception in the first place?
Also if I have:
while (!Thread.currentThread().isInterrupted()){
//do something
callMethod();
}
private void callMethod(){
//do something
try {
Thread.sleep(5000);
} catch(InterruptedException e){
}
}
again will my while loop break?
Actually your question is more about try - catch - finally than about multithreading.
1) If sleep throws an Exception, the catch block will execute and then the while loop continues.
2) You do the exact same thing as in 1)
To leave the while loop, do:
try{
while(!Thread.currentThread.isInterrupted){
//do something
Thread.sleep(5000);
}
}
catch(InterruptedException e){
}
In that case, if an Exception is thrown, the while loop is left and the catch block is executed.
Calling interrupt on a thread does not in itself throw an exception. Sleeping or waiting while the interrupt flag is set is what causes InterruptedException to be thrown.
It is totally predictable what can throw InterruptedException, so that the thread being interrupted has control and it can choose how to respond. It's a checked exception so it's evident what throws it. It is not like ThreadDeath, which can be thrown anywhere.
When an InterruptedException is thrown the thread's interrupted status is reset. If you want to restore the thread's interrupted status, because you want to check the flag later and have it be true, call Thread.currentThread().interrupt() in order to set it.
Nothing out of the ordinary happens during interruption to change how instructions get processed. So if you choose to catch the InterruptedException in a loop and check the flag to get out, you will need to reset the flag:
while(!Thread.currentThread().isInterrupted()){
//do something
try{
Thread.sleep(5000);
} catch(InterruptedException e){
Thread.currentThread().interrupt();
}
}
Alternatively you can use the InterruptedException to get out of the loop:
try {
while (!Thread.currentThread().isInterrupted()) {
// do something
Thread.sleep(5000);
}
} catch (InterruptedException e) {
// flag value is not used here, but still good style
Thread.currentThread().interrupt();
}
If this last snippet is the whole run method of the thread being interrupted, you can get by without setting the interrupted status again, but if you have components being used by other parts you don't want one badly-behaved part to squelch the interrupted flag so that other code in the thread is not aware of the interruption.
Thread.sleep() will clear the "interrupted status" before throwing InterruptedException. You need to call Thread.currentThread().interrupt() in the catch block, otherwise the while condition will most likely not succeed, because the thread will always be "not interrupted" when callMethod returns.
The exception is not caused by the interrupt() method, but by sleep() blocking on a thread that has been signaled as "interrupted". This is explained in more detail here. See also this answer.
Related
After reading several SO posts on how to kill a Java thread, I fairly understand why stop is unsafe and how to handle the graceful stop.
But the solutions are targeting towards UI threads where repainting is the problem and not really a long running - blocking process executed by a thread.
Links:
How do you kill a Thread in Java?
https://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html
One precise point that I fail to understand from the solutions or examples is what is the long-running-part the samples are trying to simulate.
Eg: In this following code, what if I set the interval to INT.MAX.
public void run() {
Thread thisThread = Thread.currentThread();
while (blinker == thisThread) {
try {
thisThread.sleep(interval); // This might take forever to complete,
// and while may never be executed 2nd time.
synchronized(this) {
while (threadSuspended && blinker==thisThread)
wait();
}
} catch (InterruptedException e){
}
repaint();
}
}
public synchronized void stop() {
blinker = null;
notify();
}
The reason am asking for this use case is that, I have a bug in a legacy code base that runs another executable in a Thread.
Now the ask if the user wishes to stop the thread, we would need to kill this thread, and the executable which is part of this thread automatically gets killed.
The way you stop a thread is by asking it - nicely - to stop. It's up to the code the thread is running to listen for and act on that request.
Specifically, the way you do it is to interrupt the thread. Your code checks for the interruption - Thread.sleep and Object.wait will throw InterruptedException if the thread is interrupted before or during their execution; but you catch the interruption, and ignore it, so you won't act on it.
Instead of this:
while (condition) {
try {
Thread.sleep(...);
wait();
} catch (InterruptedException e) {
}
}
Put the interruption outside the loop:
try {
while (condition) {
Thread.sleep(...);
wait();
}
} catch (InterruptedException e) {
}
then the loop terminates if it is interrupted.
I've used Thread.sleep for all kinds of different reasons, but one thing I've never understood is when an exception would occur during this try /catch block:
try {
Thread.sleep(1000); // sleep for 1 second.
} catch (Exception x) {
fail("Failed due to an exception during Thread.sleep!");
x.printStackTrace();
}
What would have to occur within the computer to actually hit an exception on Thread.sleep? My best guess, would be that maybe the system clock has a once in a lifetime "skip of a beat" like a heartbeat, but how often does this happen..
So in essence, my question is: When executing Thread.sleep, what would have to occur internally for #sleep to throw an exception?
If you look in the JavaDoc for Thread.sleep() you see exactly what might happen:
Throws:
IllegalArgumentException - if the value of millis is negative
InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.
An example on how to interrupt another thread might look like this:
public class Foo {
public static void main(final String[] args) throws Exception {
Thread sleepThread = new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Interrupted!");
}
}
});
sleepThread.start();
Thread.sleep(500);
sleepThread.interrupt();
}
}
This will print
Interrupted!
The Thread class defines an interrupt method. When it's called (obviously from another thread) by a thread and there's no security exception, an InterruptedException is thrown.
The purpose is, precisely (and normally), to interrupt the sleep.
Thread.sleep(someValue) can fire InterruptedException.
More info about handling this exception and reson for this you can find here.
You can find a lot usefull answers on SO. Here is the one for example:
When does Java's Thread.sleep throw InterruptedException?
When a thread interrupt is issued, for example if a signal was sent to shut the JVM down.
The Thread can throw an InterruptedException (which you should use instead of general Exception) when the Thread is interrupted (usually by the interrupt() method called from another Thread) instead of just waiting. It has nothing to do with the sleep() method.
This question already has answers here:
Does a finally block always get executed in Java?
(51 answers)
Closed 9 years ago.
I have this java code with nested try:
try
{
try
{
[ ... ]
{
catch (Exception ex)
{
showLogMessage(ex);
return;
}
while (condition == true)
{
try
{
[ ... ]
{
catch (Exception ex)
{
showLogMessage(ex);
continue;
}
[ ... ]
}
}
catch (NumberFormatException e)
{
showLogMessage(e);
}
finally
{
doSomeThingVeryImportant();
}
I want to know if finally is always executed when I get an exception. I ask this because catch blocks have return or continue statements.
When is doSomeThingVeryImportant() executed? When I get an Exception on when I get a NumberFormatException?
I only want if after any catch block is executed, the finally block is executed also.
The finally block, if used, is placed after a try block and the catch blocks that follow it. The finally block contains code that will be run whether or not an exception is thrown in a try block. The general syntax looks like this:
public void someMethod{
Try {
// some code
}
Catch(Exception x) {
// some code
}
Catch(ExceptionClass y) {
// some code
}
Finally{
//this code will be executed whether or not an exception
//is thrown or caught
}
}
There are 4 potential scenarios here:
The try block runs to the end, and no exception is
thrown. In this scenario, the finally block will be
executed after the try block.
An exception is thrown in the try block, which is
then caught in one of the catch blocks. In this scenario,
the finally block will execute right after the catch block
executes.
An exception is thrown in the try block and there's
no matching catch block in the method that can catch
the exception. In this scenario, the call to the method
ends, and the exception object is thrown to the enclosing
method - as in the method in which the try-catch-finally
blocks reside. But, before the method ends, the finally
block is executed.
Before the try block runs to completion it returns to
wherever the method was invoked. But, before it returns
to the invoking method, the code in the finally block is still
executed. So, remember that the code in the finally block
willstill be executed even if there is a return
statement somewhere in the try block.
Update: Finally ALWAYS gets executed, no matter what happens in the try or catch block (fail, return, exception, finish etc.).
The finally block always executes when the try block exits (click).
Yes, Finally always executes. With exception and with NO exception.
It's the way to be sure some portion of code get always executed.
Used for example, to dispose objects, to close opened server connections and that kind of stuff.
Check this link from oracle:
http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
Yes, finally blocks are always executed.
Source: http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
Yes; or, at least, as close to "always" as possible. (So, even if you have a return or another throw.)
If your process is killed, or your program gets stuck in a deadlock or infinite loop, or your device is struck by a meteor, then program flow will not reach the finally block.
Say your code block is something like this :
try
{
try
{
System.out.println("first try block");
}
catch (Exception ex)
{
System.out.println("first cathc block");
return;
}
while (true)
{
try
{
System.out.println("second try block...");
}
catch (Exception ex)
{
System.out.println("second catch block");
continue;
}
System.out.println("end of loop");
break;
}
}
catch (NumberFormatException e)
{
System.out.println("last catch block");
}
finally
{
System.out.println("finally block");
}
If you run this then the output that you will get is :
first try block
second try block...
end of loop
finally block
So finally block gets executed anyway.
The finally block always executes when the try block exits.
This ensures that the finally block is executed even if an unexpected exception occurs
Taken from here: http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
Further, the page explains that the finally block may not be executed if the JVM exists while the try or catch code is being executed, or if the thread executing the try/catch is interrupted or killed.
So unless you may kill the JVM or the try/catch is beeing executed in a thread, the finally block will always be executed
Yes, finally blocks are always executed. But terms and conditions apply .
Untill unless you call System.exit();
Yes finally always gets executed and its because one can program to close/handle resources in case of exceptions or no exception without fail.
http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
Update to answer the question in comment about System.exit()
The finally block will not execute in case of System.exit() unless it fails with some SecurityException.
Update after question changed. No matter what the exception is finally block will always execute.
If its Exception then your catch block will not execute as it catches only NumberFormatException
No, finally won't get execute always. There are two situations where Finally won't get execute.
Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
java reference
For your question, if these two things are not there, whatever inside your finally will get executed, that's sure.
I am trying to construct two threads, thread A is the main thread and thread B is the second thread, thread B is updating a variable through a time consuming function (this variable should be shared between both threads, because eventually thread A needs to use that variable as well), but I want thread A to terminate thread B if thread B takes too long to complete (using an exception).
What I tried is the following:
Thread thread = new Thread() {
public void run() {
/// run something that could take a long time
}
};
synchronized (thread) {
thread.start();
}
System.err.println("Waiting for thread and terminating it if it did not stop.");
try {
thread.wait(10000);
} catch (InterruptedException e) {
System.err.println("interrupted.");
}
Should that give the expected behavior of terminating a behavior in case it has run more than 10 seconds? The thread object gets deleted after the wait, because the method that runs the thread returns.
Right now, what happens with this code is that I always get java.lang.IllegalMonitorStateException on the wait(10000) command.
You will always get a IllegalMonitorStateException if you are calling wait() on an object that you are not synchronized on.
try {
// you need this to do the wait
synchronized (thread) {
thread.wait(10000);
}
} catch (InterruptedException e) {
System.err.println("interrupted.");
}
If you are waiting for the thread to finish then you probably are trying to do a:
try {
thread.join(10000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println("interrupted.");
}
Unfortunately, you do not know at that point if the thread is running because join doesn't return whether or not it timed out (grumble). So you need to test if the thread.isAlive() after the join.
If you are asking how you can cancel the thread if it runs for longer than 10000 millis, then the right thing to do is use thread.interrupt(). This will cause any sleep() or wait() methods to throw an InterruptedException and it will set the interrupt flag on the thread.
To use the interrupt flag your thread should be doing something like:
while (!Thread.currentThread.isInterrupted()) {
// do it's thread stuff
}
Also, it is always a good pattern to do something like the following because once the InterruptedException is thrown, the interrupt flag has been cleared:
} catch (InterruptedException e) {
// set the interrupt flag again because InterruptedException clears it
Thread.currentThread.interrupt();
System.err.println("interrupted.");
}
That code is incorrect. Method wait is declared in Object class and is intended to suspend current thread using as monitor instance of the object on which it is called. You may invoke this method only in synchronized section, that is why you get your exception.
Regarding to your problem: in general you can not stop another thread if it does not want to stop. So you should invoke Thread.interrupt to notify the thread that it should stop working and it is up to that thread to decide to take into account that notification or not. To check if thread is interrupted you may use interrupted() or isInterrupted() methods.
In Effective Java (page 275), there is this code segment:
...
for (int i = 0; i < concurrency; i++) {
executor.execute(new Runnable() {
public void run() {
ready.countDown();
try {
start.await();
action.run();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
done.countDown();
}
}
}
...
What's the use of catching the interrupted exception just to re-raise it? Why not just let it fly?
The simple answer is that InterruptedException is a checked exception and it is not in the signature of the Runnable.run method (or the Executable.execute() method). So you have to catch it. And once you've caught it, calling Thread.interrupt() to set the interrupted flag is the recommended thing to do ... unless you really intend to squash the interrupt.
Sometimes you can't ignore exception and you must catch it. Mainly this happens when you override method which can't throw InterruptedException in accordance with its signature. For example, this approach is usually used in Runnable.run() method.
The executor can interrupt tasks if they are cancelled but it clears the interrupted flag between tasks to avoid one cancelled task interrupting an unrelated task.
As such, interrupting the current thread here would be dangerous if it actually did anything.
A simpler way around this is to use Callable or ignore the interrupt.
Additionally it is a good idea to catch and log any error or exception thrown in the try/catch block otherwise the exception/error will be discarded and your program could be failing but you won't know it is or why.