Why a thread would interrupt another thread [duplicate] - java

This question already has answers here:
What kind of behaviour causes an interrupted exception?
(7 answers)
Closed 9 years ago.
In Java multi threaded applications, we deal with InterruptedThreadException. This Exception is thrown if another thread interrupts the current thread. Now what is the reason another thread might want to interrupt the current thread when it knows that it is going to cause an Exception?

Many reasons. But the most popular one is to cancel some task on a thread.
See http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html for details.

In most cases, to notify that a Thread should abort. Usually, a worker thread executing some sort of batch operation is implemented in a way that it terminates itself (i.e. exit out of its run() method) when interrupted.
Unfortunately, a lot of programmers simply catch and swallow it which is a very very bad practice. If a Thread is not expecting an InterruptedException it should either re-throw or should restore its interrupted status if it cannot throw it (if restrained by an Interface for example) by calling
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}

Related

Why is a try catch statement required? [duplicate]

This question already has answers here:
Why do I need to handle an exception for Thread.sleep()?
(3 answers)
Closed 4 years ago.
Why is a try/catch exception handling statement required in Java for the below line:
TimeUnit.MILLISECONDS.sleep(250);
I just want my code to sleep for 250 milliseconds before executing the next line. Why is a try-catch statement required? I can’t forsee any exceptions with this. The sleep function in python doesn't require a try catch.
The exception I get in the IDE without adding the try catch is:
Error:(124, 40) error: unreported exception InterruptedException; must be caught or declared to be thrown
When I surround it in the try catch as per below it works fine:
try {
TimeUnit.MILLISECONDS.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
You need to catch the exception simply because the thread running (sleeping) might be interrupted and you need to catch the interruption.
From the Oracle description of the InterruptedException
Thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity.
Interrupting a thread that is sleeping is a very important part of Java. It provides control when you need to stop an application (or a process) and do not want to be halted from doing so due a thread sleeping. The InterruptException allows developers to catch interrupt attempts and deal with it.
Maybe your beef is with checked exceptions in general.... which is a feature of Java that many people do not like. We can understand your frustration with checked exceptions. You can read up more on checked exceptions in Java via Google.

How to handle InterruptedException of BlockingQueue? [duplicate]

This question already has answers here:
Handling InterruptedException in Java
(7 answers)
Closed 6 years ago.
I have a code similar to this which is inside run() method of a Runnable and multiple instances of that Runnable get launched,
do{
try{
String contractNum=contractNums.take();
}catch(InterruptedException e){
logger.error(e.getMessage(), e);
}
}while(!("*".equals(contractNum)));
Where contractNums is a BlockingQueue<String> shared by multiple threads. There are separate Runnables putting elements to this queue.
I am not sure about next steps after catching InterruptedException, should I terminate this thread by re throwing a RuntimeException ( so my while loop terminates ) or try to take next element from contractNum queue again and ignoring InterruptedException?
I am not sure if InterruptedException to be treated as a fatal condition for thread to terminate or keep it in while loop.
Please suggest.
7.1.2 Interruption policies
Just as tasks should have a cancellation policy, threads should have
an interruption policy. An interruption policy determines how a thread
interprets an interruption request—what it does (if anything) when one
is detected, what units of work are considered atomic with respect to
interruption, and how quickly it reacts to interruption. The most
sensible interruption policy is some form of thread-level or service-
level cancellation: exit as quickly as practical, cleaning up if
necessary, and pos- sibly notifying some owning entity that the thread
is exiting. It is possible to establish other interruption policies,
such as pausing or resuming a service, but threads or thread pools
with nonstandard interruption policies may need to be restricted to
tasks that have been written with an awareness of the policy.
7.1.3 Responding to interruption
As mentioned befor, when you call an interruptible blocking method
such as Thread.sleep or BlockingQueue.put , there are two practical
strategies for handling InterruptedException :
• 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.
Java Concurrency in Practice Chapter 7.
Specifically in your code you will need to make sure that if thread is interrupted your application logic is not broken.
And it is indeed better to catch your interruption exception. What to with it is up to you just try to make sure that you don't break the application logic.
It depends. Are there places where you intentionally interrupt the thread, for example to tell it to finish up (for example during shutdown)? If not, you just need to handle possible spurious interrupts that will wake up the thread. If you don't want the processing to be affected, just ignore them. They're in absolutely no way fatal exceptions, and you don't need to log them (especially as errors).

Thread Interrupts. Can someone explain me the output to understand interrupts better? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am able to understand Threads and interrupts. I was trying to map the underlying concepts learnt from Oracle tutorial to understand concept of interrupts better. I developed this example and tried hard to understand the output as how interrupts are playing a role here. I just did not understand. So my notion was to ask someone to help me understand the output of this program which will clear me more about underlying functionality of interrupts.
public class ThreadSleepTest {
public static void main(String[] args) throws InterruptedException {
MyRunnable myRunnable = new MyRunnable();
Thread one = new Thread(myRunnable);
one.setName("Fred");
Thread two = new Thread(myRunnable);
two.setName("Lucy");
Thread three = new Thread(myRunnable);
three.setName("Ricky");
one.start();
two.start();
three.start();
//Thread.sleep(1000);
one.interrupt();
}
}
class MyRunnable implements Runnable {
public void run() {
for (int x = 1; x < 4; x++) {
System.out.println("Run by: " + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
System.out.println("Exception occured");
}
}
System.out.println("Do something");
}
}
Here is the output from my console.
Run by: Lucy
Run by: Fred
Run by: Ricky
Exception occured
Run by: Fred
Run by: Fred
Run by: Lucy
Run by: Ricky
Do something
Run by: Lucy
Run by: Ricky
Do something
Do something
Once a thread is interrupted, it is basically taken out of operation as per my understanding.
No, your understanding is incorrect. Once a thread is interrupted, it is up to the programmer who wrote the run method to decide what to do about it.
Thread termination is entirely up to the programmer, as the JVM doesn't actually know what resources and locks you may need to clear up when you terminate the thread. This is the reason why the methods stop() and suspend() in Thread have been deprecated. They are not safe.
So when a thread is interrupted, if you are in a method that throws an InterruptedException, you have to react to this exception and finish whatever it is you are doing, and if you are in the middle of your own stuff, you have to check the interrupted() status of the current thread from time to time, and if an interrupt occured, finish up what you are doing.
Here is what you chose to do when your thread is interrupted:
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
System.out.println("Exception occured");
}
In your catch clause, you are merely printing the fact that the exception occured. You are not actually doing anything towards termination of the thread. Therefore, it will not be terminated. You'll go out of the catch clause, and continue with the next iteration of your loop.
Thread.sleep() by convention clears the interrupted flag when it throws the InterruptedException. So in the next iteration, the thread is no longer "interrupted", and sleep() does not throw the exception again.
Interrupting a thread means signaling it to stop doing what it currently does.
Most I/O and locking operations will interrupt when the thread the run on is interrupted and an InterruptedException is raised in that thread (however, not all operations do so, for example see https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Semaphore.html#acquireUninterruptibly()).
The code is then able to process the exception in any way he/she sees fit. After the InterruptedException is raised, the interrupt signal is consumed, the thread can continue to do anything. In your example, the Thread.sleep() call finishes earlier, the InterruptedException is thrown and a message is logged. After that, the thread continues the for loop. Of course, the thread can be later interrupted.
I think the Java Concurrency in Practice (JCiP), page 138 gives a fairly good explanation of what might be happening. There are a few things that you can note:
The main thread creates and starts 3 threads named: Fred, Lucy, Ricky. Let's just consider the thread named Fred, which is assigned to the variable one (There are better ways of doing this e.g. the CountdownLatch).
Fred, after being scheduled to run is immediately put to sleep by your code. The method Thread.sleep is a well-designed blocking call. This means that it can be interrupted by sending an interrupt. This is exactly what main thread tries to do: request an interruption in whatever activity thread one is doing or not doing (since it's just sleeping in this case). The main thread does that by simply calling the interrupt() method on one. Note that this is perceived only as a 'friendly request' by the thread being interrupted.
In the case when you see the output 'Exception occurred', the (sleeping) interrupted thread acknowledges the interrupt and like it is documented, an InterruptedException is thrown. This exception is caught by one and the message 'Exception occurred' is printed on the stdout. Thus, the main thread has succeeded in interrupting what one was doing.
Other threads do their tasks without interruption (that's why you see the other print statements).
If you interrupt a thread, the next or current time you sleep or wait in this thread its going to throw an InterruptedException. BUT the interrupted state is cleared with this. If your Thread is interrupted, you should terminate it in the near future.

Thread.stop() and finally [duplicate]

This question already has answers here:
Are Thread.stop and friends ever safe in Java?
(8 answers)
Closed 7 years ago.
I created a following Class named as ThreadClass (which is a thread as you can see),its structure is something like the following
class SomeTask implements Runnable
{
boolean someCondition=true;
public void run() {
try
{
while(someCondition)
{
//Here goes the Process Code
}
}
catch(Exception errorException)
{
//Catching the Exception
}
finally
{
////I expect that this finally should run every time ,whatever happens in the world
}
}
}
My question is about the finally block and the stop() method
As above class is implementing Runnable, so I can create the object of this class and start a thread of it by calling start() method.I am also aware of the fact that I can stop this thread by using stop() (Yes , I know it is deprecated) method .
What I want to clarify myself is that, if somehow I need to call the stop method on the ThreadClass's object, then can I rely on the finally block to execute even if the thread is stopped by calling stop() as I am doing some important closing things in the finally block.
Thread#stop works by throwing a ThreadDeath exception, it doesn't obliterate the thread instantaneously the way System.exit blows away the JVM. ThreadDeath can even be caught, although that's not a good idea. So try blocks are still relevant.
However, complicating this is that if the thread has stop called on it multiple times then, if the second stop is called when the thread is in a finally block then it could be thrown from the finally block so that the finally block would not complete then. And if the thread's cleanup takes a while then it might be likely that stop could be called more than once on it.
Or even if you only call stop once, if at the time that stop is called the thread happens to be already executing its finally block, then the stop would interfere with completing the finally block.
This is similar to what the technotes on Thread primitive deprecation point out:
1) A thread can throw a ThreadDeath exception almost anywhere. All synchronized methods and blocks would have to be studied in great detail, with this in mind.
2) A thread can throw a second ThreadDeath exception while cleaning up from the first (in the catch or finally clause). Cleanup would have to repeated till it succeeded. The code to ensure this would be quite complex.
So there are some cases that are problematic, it would be very difficult to make sure cleanup gets done properly. James' comment is correct, if at all possible you should use interruption for this kind of thing so that the thread can reliably finish its business.

why need to catch InterruptedException in the Sleep? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When does Java's Thread.sleep throw InterruptedException?
I saw we have to catch InterruptedException in the Thread.Sleep method, why? I never saw this exception occured in the real time. Any clue?
This happens if thread#1 is sleeping, and another thread interrupts it. This is usually an attempt to stop thread#1. For example, thread#1 is sleeping while doing some long-running task (perhaps in background) and the user hits a cancel button.
The IterruptedExeption is thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity. Occasionally a method may wish to test whether the current thread has been interrupted, and if so, to immediately throw this exception. The following code can be used to achieve this effect:
if (Thread.interrupted()) // Clears interrupted status!
{
throw new InterruptedException();
}
Every thread has a Boolean property associated with it that represents its interrupted status. The interrupted status is initially false; when a thread is interrupted by some other thread through a call to Thread.interrupt(), one of two things happens. If that thread is executing a low-level interruptible blocking method like Thread.sleep(), Thread.join(), or Object.wait(), it unblocks and throws InterruptedException. Otherwise, interrupt() merely sets the thread's interruption status. Code running in the interrupted thread can later poll the interrupted status to see if it has been requested to stop what it is doing; the interrupted status can be read with Thread.isInterrupted() and can be read and cleared in a single operation with the poorly named Thread.interrupted(). See.
There is no way to simply stop a running thread in java (don't even consider using the deprecated method stop()). Stopping threads is cooperative in java. Calling Thread.interrupt() is a way to tell the thread to stop what it is doing. If the thread is in a blocking call, the blocking call will throw an InterruptedException, otherwise the interrupted flag of the thread will be set.
The problem is that blocking calls like sleep() and wait(), can take very long till the check can be done. Therefore they throw an InterruptedException. (However the isInterrupted is cleared when the InterruptedException is thrown.)

Categories