Who interrupts my thread? - java

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, ...

Related

What is the reason of clearing of thread's interrupt status by Thread.interrupted()? [duplicate]

This question already has answers here:
Why do InterruptedExceptions clear a thread's interrupted status?
(4 answers)
Closed 2 years ago.
In many sources I found that Thread.interrupted() method clears interrupt status of thread, but in none of them there was explanation of the reason why this method works exactly in this way.
I still feel confused a little because of lack of understanding of this reason and lack of understating of what problem designers of java tried to solve by clearing interrupt status.
I will appreciate very much if someone could explain that and show some example.
The idea behind thread interruption is that one thread may signal another to request that it interrupt is regular processing to divert its attention to some thread-specific special action. What a thread actually does in response depends entirely on the code running in that thread.
There are two main ways in which a Thread can determine whether it has been interrupted:
Several Thread and Object methods will throw an InterruptedException if invoked in a thread whose interrupted status is set, or if a thread is interrupted while the method is executing. The interrupted status is cleared in this event, presumably because the exception is considered adequate notice of the interruption.
Code running in the thread can invoke Thread.interrupted() or Thread.currentThread().isInterrupted() to proactively test for an interrupt. The former also resets the interrupted status; the latter does not, likely because it is an instance method -- interrupts must not be lost in the event that one thread calls the isInterrupted() method of a different one.
The techniques that cause the interrupt status to be reset do so in order that the thread is able to handle subsequent interruptions. The key point here is perhaps that thread interruption is not intended to necessarily cause the interrupted thread to shut down (although that is indeed one response that a thread can make). It is a more general mechanism.
From jdoc
An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate
and
By convention, any method that exits by throwing an InterruptedException clears interrupt status when it does so. However, it's always possible that interrupt status will immediately be set again, by another thread invoking interrupt.
So Thread.interrupted clears the flag because it's always possible that interrupt status will immediately be set again, by another thread invoking interrupt.
Explanation https://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html

Interrupted Exception occurrence reason

While going through the javadoc for the notifyAll() method under Object class came through the following lines:
If the current thread is interrupted by any thread before or while it is waiting, then an
InterruptedException is thrown. This exception is not thrown until the lock status of this object has been restored as described above.
The point is:
the current thread is interrupted while it is waiting
What does this means? Can a thread be interrupted while it is waiting?
If yes, why? What is the use of it?
The meaning of "thread getting interrupted" in Java means that the thread's interrupted flag has been set, nothing more. However, most methods of the JDK which make the thread wait will immediately find out about this and exit the wait state, throwing an InterruptedException. Such is the case with the methods you have been reading about.
A thread can be interrupted while waiting if another thread calls:
waitingThread.interrupt();
This can happen if you do it yourself of course but also if you use a framework to manage your threads, typically an executor service, and call some of the methods that interrupt the underlying threads (e.g. shutdownNow or if you call future.cancel(true); on the Future returned by the submit method).
The interruption mechanism is how Java enables one thread to tell another one to stop what it is doing and is therefore extremely useful.

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.

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.

What kind of behaviour causes an interrupted exception?

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.

Categories

Resources