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

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.

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.

Why does Threads in BLOCKED state do not get interrupted?

I am working on multithreading in java.
Want to understand if a Thread is in BLOCKED state why it cant be interrupted? And why the thread can be interrupted only if it is in WAIT state? Basically, why do we need two Thread states one which can be interrupted and the other which cant be interrupted?
This question might be very basic but, I am trying to understand things rather than just remembering them.
One assumes that you mean cause the thread to stop its current operation and throw an InterruptedException? A thread interrupt in Java is just a flag. You can call interrupt() just fine on a BLOCKED thread and that flag will be seen next time code checks for it.
The principle problem with implementing such a functionality is, how is a keyword (synchronized) supposed to throw an exception? InterruptedException is a checked exception, it would not be a useful exercise to have to declare every synchronized method (and block) in the language with throws InterruptedException!
An interrupt is a communication tool, it's generally for letting a thread know about a system state it needs to check on. The name is a legacy carry over/upward from flags set within hardware to let microprocessors know about a particular state (such as new values set on some input pins) that needs to be examined. Do not read too much into the name "interrupt" and think it's meant to be a tool for breaking the flow of the program within another thread. It is not. Hence even the methods that do throw an exception declare it as checked, the other thread is free to ignore it and resume waiting if it wants. Being able to arbitrarily break another thread's BLOCKED state would break the program flow, which is not the purpose.
Blocked Threads can receive Interrupts. You may have to check Thread.currentThread().interrupted() to see whether Thread got interrupt when it was waiting to acquire any resource.
See Also Lock::lockInterruptibly()
A blocked thread can be interrupted. Here is how interrupt is called on a thread depending on which state it is. From javadocs:
The checkAccess method of this thread is invoked, which may cause a
SecurityException to be thrown.
If this thread is blocked in an invocation of the wait(), wait(long),
or wait(long, int) methods of the Object class, or of the join(),
join(long), join(long, int), sleep(long), or sleep(long, int), methods
of this class, then its interrupt status will be cleared and it will
receive an InterruptedException.
If this thread is blocked in an I/O operation upon an interruptible
channel then the channel will be closed, the thread's interrupt status
will be set, and the thread will receive a ClosedByInterruptException.
If this thread is blocked in a Selector then the thread's interrupt
status will be set and it will return immediately from the selection
operation, possibly with a non-zero value, just as if the selector's
wakeup method were invoked.
If none of the previous conditions hold then this thread's interrupt
status will be set.
Interrupting a thread that is not alive need not have any effect.
Throws: SecurityException - if the current thread cannot modify this
thread

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

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