What kind of behaviour causes an interrupted exception? - java

I'm relatively new to Threading in Java and I've noticed that everytime I use Thread.sleep() I have to catch InterrupetdException.
What kind of behaviour causes this, and in simple applications where I have a monitor thread can I just Ignore the exception?

It happens when something calls interrupt() on the thread. This article by Brian Goetz explains the interruption mechanism and how you should handle InterruptedExceptions:
"The most common response to InterruptedException is to swallow it -- catch it and do nothing (or perhaps log it, which isn't any better) -- as we'll see later in Listing 4. Unfortunately, this approach throws away important information about the fact that an interrupt occurred, which could compromise the application's ability to cancel activities or shut down in a timely manner."
"If you catch InterruptedException but cannot rethrow it, you should preserve evidence that the interruption occurred [...]. This task is accomplished by calling interrupt() to "reinterrupt" the current thread."

As others have said, it is caused by some other thread calling interrupt() on the Thread object that is sleeping.
What this means in plain english, is that some other thread has decided to cancel the sleeping thread. The try/catch block is there so you can gracefully handle the cancellation of the thread, and safely clean up any resources, or shut down whatever operation it was doing correctly.
If you don't actually need to do any of that, then yes, you still need an empty catch block. But that's Java for you...​​​​​​​​​​​​​​​​​​​​

Some advices from Java Concurrency in Practice:
Propagate the exception (possibly after some task-specific cleanup), making your method an interruptible blocking method, too; or
Restore the interruption status so that code higher up on the call stack can deal with it.
Only code that implements a thread's interruption policy may swallow an interruption request. General-purpose task and library code should never swallow interruption requests.

The primary case is when someone calls Thread.interrupt() on your thread.
It may be safer to throw a RuntimeException if it happens when you're really not expecting it, but for very simple cases you can probably ignore it.

From the javadocs:
Class InterruptedException
Thrown when a thread is waiting,
sleeping, or otherwise paused for a
long time and another thread
interrupts it using the interrupt
method in class Thread.
Hope that answers your question.

Well if some other Thread calls thread.interupt(), while the thread is sleeping, you'll get the Exception. And yes, you can probably just put try..catch arround the sleep() and ignore it ;)

InterruptedException is a checked exception so unfortunately you cannot just ignore it. In most simple cases you do not have to do anything in the catch clause because you are sure that it will not happen.
From the API
Thrown when a thread is waiting, sleeping, or otherwise paused for a long time and another thread interrupts it using the interrupt method in class Thread.

Related

How can I immediately terminate a Thread? (Not interrupt)

This is not a question about how to cleanly terminate a thread, ie by calling interrupt on it and having the thread respond appropriately. I cannot modify code the thread is executing in any way.
I specifically want to immediately terminate a Thread, I don't care at all what state things are left in. I know something similar is possible using Thread.stop, however this actually throws a ThreadDeath exception, and for the Thread to terminate this exception cannot be caught. However the code I am dealing with catches this exception and is not rethrowing it.
Thread.destroy() seemed to be what I was looking for, however this method was never implemented. Is there any other way of achieving this?
I believe that there's no way in Java to just kill off a thread like you're describing. As you note in a comment, interrupt won't do what you want. If the thread is executing, it just sets a flag and it's up to the thread to notice it. if the thread is waiting or sleeping, it will throw an InterruptedException.
The only way I can imagine doing what you're describing is to kill the process in which the thread is running. (E.g., call System.exit(int).)
No there isn't a way. From Java Concurrency in Practice:
Since there is no preemptive way to stop a thread, they must instead
be persuaded to shut down on their own.
Interrupting a thread is not the cleaner way as you said. Clean ways could be:
ExecutorService.shutdown()
Future.cancel()
Poison Pills
You aren't meant to submit tasks to threads that take ages to be done. You would rather divide them into smaller tasks and send a poison pill to cancel the bigger task. If there is not a way to do that, then spawn/fork a process and kill it if you want to cancel the task.
If you don't trust the thread in question to the point that you need to kill it, you would probably be better off running it in a separate process, and kill the process instead.
Anyway, the following code might work if you are ok with the deprecated Thread methods:
while (theThread.isAlive()) {
theThread.stop();
}
Depending on how badly the thread is trying to survive…
You might want to run this code in several threads or repeat the stop() call if that's not enough. However, I managed to kill the following thread with this code:
final Thread iWontDie = new Thread(() -> {
int i = 0;
while (true) {
try {
System.out.println("I'm still alive! " + ++i);
} catch (Throwable t) {
// eat t
}
}
});
iWontDie.start();
If you are on Java 7 or earlier, you could use the overloaded stop(Throwable obj) method to throw something besides a ThreadDeath error:
Forces the thread to stop executing. If the argument obj is null, a NullPointerException is thrown (in the current thread). The thread represented by this thread is forced to stop whatever it is doing abnormally and to throw the Throwable object obj as an exception. This is an unusual action to take; normally, the stop method that takes no arguments should be used.
This method, like the parameterless version, is deprecated, so just keep that in mind.

Why doesn't Thread.stop work in situations where Thread.interrupt doesn't work?

The official Sun Oracle stance on Thread.stop() is that it should not be used. Among other arguments, they write:
It should be noted that in all situations where a waiting thread doesn't respond to Thread.interrupt, it wouldn't respond to Thread.stop either.
But I do not understand that. If a thread is busy actively working on something (not just waiting or blocking on an external resource) and doesn't explicitly check the interrupt flag, wouldn't Thread.interrupt() do nothing while Thread.stop() will still work (throw ThreadDeath)?
But I do not understand that. If a thread is busy actively working on something (not just waiting or blocking on an external resource) and doesn't explicitly check the interrupt flag, wouldn't Thread.interrupt() do nothing while Thread.stop() will still work (throw ThreadDeath)?
I think you misunderstand the quoted text. It refers to a thread that is waiting, not a thread that is running. Specifically, it is referring to cases like the following:
When the thread is blocked in an I/O call, low-level JVM implementation issues prevent it responding to either a stop or an interrupt.
A thread that doesn't want to be stopped can catch ThreadDeath, and this is analogous to a thread that doesn't want to be interrupted simply ignoring the flag.
Thread.stop is not an issue about being good or bad coding with regard to being able to bail out threads.
You should not use it unless as a very last resort. It is possible to do your code and expect Thread.stop() to occur but in that case interrupt() will possible do just as fine.
The issue that stop() won't work where interrupt() doesn't (i.e. blocked on some native stuff): both stop and ineterrupt would use the same native signals to carry the call.
On POSIX, if SIGUSR2 (for instance) doesn't help the native code to bail out, it won't help either of interrupt/stop.
You can think of interrupt vs stop like that: both may use OS signals. The OS signals may not be honored by the native code. However, if they are: stop() also puts a Throwable on the stack that will be propagated in the java code. On the contrary interrupt only sets a flag.
The throwable, however, may pop-up in virtually any statement, so some invariants may fail to be properly handled.
Possibly, it's partly fixable via Thread.uncaughtExceptionHandler by throwing away large states, rolling back transactions, etc... Again: not advisable.
The main reason, as far as I understand, is that the ThreadDeath exception may be thrown anywhere, whereas the interupt flag has to be checked explicitly.
Consider this code running in a thread:
public void sellItem(Store s) {
synchronized (s) {
if (s.itemsAvailable > 0) {
s.itemsAvailable--;
s.itemsSold++;
}
}
}
If a ThreadDeath is thrown after s.itemsAvailable--, the Store object is left in an inconsistent state. On the other hand, this code is safe:
public void sellLoop(Store s) {
while (!Thread.interrupted())
sellItem(s);
}
Source: http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#stop%28%29
They say that Thread.stop() would not work because (I guess) the throwable can be caught and ignored.
if the JVM is too busy to interrupt the thread, it's also too busy to kill it.

What happens when you invoke a thread's interrupt()?

I need to know what happens
when it is sleeping?
when it is running i.e., it is executing the given task.
Thanks in advance.
Interrupting a thread is a state-safe way to cancel it, but the thread itself has to be coded to pay attention to interrupts. Long, blocking Java operations that throw InterruptedException will throw that exception if an .interrupt() occurs while that thread is executing.
The .interrupt() method sets the "interrupted" flag for that thread and interrupts any IO or sleep operations. It does nothing else, so it's up to your program to respond appropriately- and check its interrupt flag, via Thread.interrupted(), at regular intervals.
If a thread doesn't check for interruptions, it cannot safely be stopped. Thread.stop() is unsafe to use. So you use .interrupt() to stop a thread, but when writing multithreaded code, it is up to you to make sure that .interrupt() will do something sensible. This TechRepublic article is a pretty good tutorial.
Judging by your previous questions, I assume you are interested in Java's behavior.
In Java, an InterruptedException will be thrown if the thread is currently blocking. If the thread is not blocking, the exception will not be thrown.
For more information, look here:
JavaDocs
For .NET languages, a ThreadInterruptedException will be thrown if the thread is currently blocking. If the thread isn't blocking the exception will not be thrown until the thread blocks.
Please tag your question with the language you want an answer for.
One more important information worth sharing is that, there are two methods in Thread Class
isInterrupted() and interrupted(). Latter one being a static method. isInterrupted() method call does not alter the state of interrupted attribute of Thread class, whereas interrupted() static method call can will set the value of interrupted boolean value to false.

Who interrupts my thread?

I understand what an InterruptedException does and why it is thrown. However in my application I get it when waiting for SwingUtilities.invokeAndWait() on a thread that is only known by my application, and my application never calls Thread.interrupt() on any thread, also it never passes the reference of the thread on to anyone.
So my question is: Who interrupts my thread?
Is there any way to tell? Is there a reason why the InterruptedException doesn't contain the name of the Thread that requests the interrupt?
I read that it could be a framework or library that does this, we use the following, but I can't think of reason for them to interrupt my thread:
Hibernate
Spring
Log4J
Mysql connector
If possible, you could extend Thread and overwrite the interrupt() method for this thread to print a stacktrace or throw an unsupported operation exception.
You could also use the extended Thread class to store a reference to the interrupting thread and read it once you catch the interrupted exception.
In general, if you want to know who is doing something, attach a debugger, put a breakpoint, and there you go. No need for guessing if you can reproduce it!
In this case, you can put a breakpoint at Thread.interrupt(). If there are other threads that are being interrupted too (so you have "false positive" hits on the breakpoint), you could add a breakpoint condition (most IDE's allow you to do that easily), for example by checking the name of the thread.
There is something strange here.
From the javadoc of invokeAndWait, an InterruptedException is thrown
if we're interrupted while waiting for the event dispatching thread to finish excecuting doRun.run()
Have you tried to see if the code executed in the EDT sends any exception ? Or do the code in that EDT tries to modify some of this thread's variables (I know this term is not "orthodox" in java language, but I hope you see what I mean : any code implying synchronized, wait, join, ...

How do I make a thread wait until a file is created?

I need a thread to wait until a file is exist or created.
I have the following code so far:
while(!receivedDataFile.isFileExists("receiveddata.txt"))
{
try {
Thead.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
return null;
}
}
When I run it, the following exception appears, and the thread ends:
java.lang.InterruptedException: sleep interrupted
A thread is interrupted when it is blocking (the call to sleep) and another thread calls its interrupt method. The call to interrupt must be made explicitly for this to happen.
Seems that repeating the check for the file would be the logical thing to do if the thread is interrupted, but without knowing the cause of the interruption it's hard to say.
As usual, when it comes to threading, Brian Goetz has something to say on the matter of InterruptedException:
http://www-128.ibm.com/developerworks/java/library/j-jtp05236.html
I must agree Bombes comment: threads don't get interrupted on their own. Contrary to Jokis comment - they're not interrupted when a thread context swap takes place either (in fact, if a thread sleeps, it will surrender it's quantum to any thread that has work to do, but I digress).
Furthermore, I would advise an alternative means of communication than polling for files. You cannot be certain, for example, that once you have spotted a file, that it has been completely written without extra work from the file-writer (such as renaming it when ready, or creating a 'ready' file).
Consider using something more 'data push' such as RMI, HTTP-POST, JMS queues, etc.
You should find out which thread interrupts that thread. Threads don’t do that on their own.
If all you want is a notification when a file is created, AND you can (and willing) to go native (JNI) AND you want only win32 support, you could use the code here.
Well, if you don't know what InterruptedException is and/or don't want to do anything about it, obviously you should at least do something besides returning and exiting your loop. Take out the return, and then you'll keep waiting.
But I'd check into why you're getting interrupted. Something is trying to cancel your thread.

Categories

Resources