Java - concurrency: LinkedBlockingQueue, "try again if failed" - java

int capacity = ...
BlockingQueue q = new LinkedBlockingQueue<Element>(capacity);
Now, I do feel mildly ridiculous asking this but I'm not particularly savvy when it comes to java concurrency, so I would appreciate some help with choosing the correct way to enqueue something (and dequeue, actually, but I expect when we cleared up the one, the other will fall into place by itself).
There is, of course
while(!q.offer(e));
But I'm a bit wary of spinning implementations in a multi-threaded environment.
And I can't do
synchronized(q){
while(!q.offer(e))q.wait();
}
either because the wakeup calls will go to internal (private) instances of Condition, meaning this would be a suicide-by-sleeping-pills implementation.
However, I'm also not particularly fond of
try{
q.put(e);
}catch(InterruptedException ex){}
(even though it does seem to be a popular choice in online examples) because although this would do the waiting for me, I know of no reliable way to detect when an exception would force me to try again.
I could do something like
boolean success = false;
do{
try{
q.put(e);
success = true;
}catch(InterruptedException ex){}
}while(!success)
But then I'd end up enqueuing the same element multiple times if the exception takes place in-between the put and the assignment to success.
I could do
boolean success = true;
do{
try{
q.put(e);
}catch(InterruptedException ex){
success = false;
}
}while(!success)
But I remember having read (way back) that you shouldn't rely on exception handling for conditionals (though I can't seem to remember the reason why this is discouraged).
So ... what options do I have? Do I need to spin or is there something more intelligent?

It is not a good practice to catch an InterruptedException as you do since your code won't be responsive to interruption anymore. An InterruptedException is usually thrown by methods that are responsive to interruptions (current Thread being interrupted) such as the methods of type await, wait, join, sleep and many others, this should not be considered as a failure but rather as it really is, a Thread's status change that needs be taken into consideration.
As Brian Goetz explains in Java Concurrency in Practice, I quote:
When your code calls a method that throws InterruptedException, then
your method is a blocking method too, and must have a plan for
responding to interruption. For library code, there are basically two
choices:
Propagate the InterruptedException. This is often the most sensible policy if you can get away with it just propagate the
InterruptedException to your caller. This could involve not catching
InterruptedException, or catching it and throwing it again after
performing some brief activity-specific cleanup.
Restore the interrupt. Sometimes you cannot throw InterruptedException, for instance when your code is part of a
Runnable. In these situations, you must catch InterruptedException
and restore the interrupted status by calling interrupt on the
current thread, so that code higher up the call stack can see that an
interrupt was issued.
So in your case, you should simply use put(E) as it will make the calling thread waits for space to become available if needed and propagate the InterruptedException in order to keep on being responsive to interruptions.
But then I'd end up enqueuing the same element multiple times if the
exception takes place in-between the put and the assignment to
success.
This can simply never happen since an assignment of a boolean will never throw any exceptions (except a NPE in case of an un-boxing). And only methods responsive to interruption can throw such kind of exceptions as explained above which is clearly not the case of an assignment.

The put() implementation would be the correct one, blocking until interrupted or successful. The offer() is a bad idea if all you are doing is spinning (see first comment for disclaimer).
As Nicolas explained, the handling of the InterruptedException is not straightforward and depends a lot on what your other code is doing, but your concern with "if the exception takes place in-between the put and the assignment to success", that can never happen: a blocking call (like put()) can throw that exception, but it cannot occur between put() and the assignment, or at the assignment.
Lastly, there's no need to synchronize on anything. The main idea in many of java.util.concurrent classes is to avoid or abstract away the explicit synchronization.

So a few points from the LinkedBlockingQueue Javadoc:
The put method will only throw exceptions in two circumstances:
The thread is interrupted, in which case you should stop whatever you're doing anyway. See this question for more about InterruptedExceptions.
The element you're inserting is null, which is another bug entirely.
So overall, you can just use put to wait for space to become available. If either of these particular exceptions is thrown, then you shouldn't retry anyway.

Related

How can I write this with concurrency on Java? [duplicate]

If a thread is interrupted while inside Object.wait() or Thread.join(), it throws an InterruptedException, which resets the thread's interrupted status. I. e., if I have a loop like this inside a Runnable.run():
while (!this._workerThread.isInterrupted()) {
// do something
try {
synchronized (this) {
this.wait(this._waitPeriod);
}
} catch (InterruptedException e) {
if (!this._isStopping()) {
this._handleFault(e);
}
}
}
the thread will continue to run after calling interrupt(). This means I have to explicitly break out of the loop by checking for my own stop flag in the loop condition, rethrow the exception, or add a break.
Now, this is not exactly a problem, since this behaviour is well documented and doesn't prevent me from doing anything the way I want. However, I don't seem to understand the concept behind it: Why is a thread not considered interrupted anymore once the exception has been thrown? A similar behaviour also occurs if you get the interrupted status with interrupted() instead of isInterrupted(), then, too, the thread will only appear interrupted once.
Am I doing something unusual here? For example, is it more common to catch the InterruptedException outside the loop?
(Even though I'm not exactly a beginner, I tagged this "beginner", because it seems like a very basic question to me, looking at it.)
The idea is that an interrupt should be handled once. If an explicit InterruptedException did not clear the "interrupt" flag then most catchers for InterruptedException would have to explicitly clear that flag. Conversely, you can "unclear" the flag by self-interruption (Thread.currentThread().interrupt()). Java's designers went for the semantics which would save keystrokes most of the time (i.e. you more often want to clear the flag than keep it set).
It shouldn't. This is an unfortunate design flaw that makes relying on interruptions a risky business, as too often library code will catch InterruptedException without resetting the thread's interrupted flag and carry on. If you happen to signal an interruption to your thread when that particular piece of broken library code is running, when your code regains execution control, it'll be left without a clue that the interruption happened.
This only needs to happen once in any place that you're calling from your code, so in order to be able to interrupt a thread and then use the interrupted bit to control your flow from inside said thread safely, you need to be 100% sure that every piece of code that you're calling does not clear the interrupted bit by mistake. This is very hard to do when libraries are involved, but even if you could account for every single library that you're using in your code, that still doesn't account for buggy JRE code that can make the same mistake.
The fact that it only takes one library (or JRE!) author to not care or think about interruptions in order to break the logic of code that requires it shows that this is the wrong default action to take. Someone who doesn't care about the thread's interrupted bit probably won't bother to reset it after catching InterruptedException – maybe they don't even know it exists! If catching InterruptedException didn't reset the thread's interrupted status, then anyone who did not know about the interrupted bit would automatically "do the right thing" and not cause a problem for any calling code relying on interruptions. Anyone who required clearing it could still do so manually, but then it'd be an explicit action which is much more likely to be correct than an usually unintended side-effect of catching the checked InterruptedException exception. As it stands right now, if you rely on the thread's interrupted bit, anyone down your calling stack that calls Thread.sleep() carelessly can potentially ruin your day.
As a result, most Java multi-threaded code will just duplicate the Java thread interrupt model with an "isRunning" instance field and some mechanism to flip it as a workaround.
Write your code like this and you won't need a flag:
try {
while (!this._workerThread.isInterrupted()) {
// do something
synchronized (this) {
this.wait(this._waitPeriod);
}
// do something else
}
} catch (InterruptedException e) {
// ignore ...
}
As #Boyan points out, it is a bad idea to squash that the interrupt exception ... in general. In this case, the context will determine whether you should squash it (as above), set the interrupt flag (again) or allow the exception to propagate. Among other things, it depends on what the interrupt means in / to your application.
That's because an InterruptedException is considered an abnormal event in which someone else tries to stop a thread from outside it.
When you want to really interrupt a thread you just break its loop condition by setting a boolean or something similar. Or you use .wait() and .notify() from inside that thread. But if you are doing wait() externally:
an exception is thrown to notify that an external thread tried to interrupt me or to make me wait
the thread continues its work because it doesn't take any order from another thread! But the raise of the exception allows you to add special handling and do whatever you want, also effectively stop the thread.

Ignoring an InterruptedException properly [duplicate]

This question already has answers here:
Why invoke Thread.currentThread.interrupt() in a catch InterruptException block?
(5 answers)
When does Java's Thread.sleep throw InterruptedException?
(8 answers)
Closed 1 year ago.
I am aware that ignoring an InterruptedException is actually a bad practice. But let's assume in my case it is necessary: it is a utils method in a deep place, which is called by different threads. Please also assume it is not possible to rethrow.
If my only option is to tell the system "ok, I will not sleep any further, but I cannot kill this thread myself. I will finish my job and hope that my caller takes care of your interruption request", is this the correct way of doing it?
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// ignore
Thread.currentThread().interrupt();
}
Does the method interrupt() do anything else other than resetting the interrupted flag?
Please also assume it is not possible to rethrow.
Impossible; you can always rethrow. throw new RuntimeException("unhandled", e); is never a compile time error - that should be your default choice for "I have no idea what this exceptions means or I cant be bothered to handle it". It's perfectly fine: It ensures that the code will be rolled up properly, you want that to happen when exceptions you can't handle / weren't expecting (heh) occur.
However, in this case, uniquely, 'I did not expect it' also means it cannot possibly happen.
InterruptedException
Note that InterruptedException cannot ever happen unless some code is explicitly doing it. You do not get interrupted when the system is running low on resources and needs you to clean up. You do not get interrupted because some code in java core or any third party library decided to interrupt you for funsies. You do not get interrupted when the user hits CTRL+C, or goes into the task manager and clicks 'end process'.
There is only one way to be interrupted, and it is when some java code running in your JVM process runs: yourThread.interrupt();.
Presumably, there are only two options:
[A] You never do this. The point is moot. Rethrow that thing using throw new RuntimeException(e); - you're writing code that is literally going to never ever run, stop worrying about it.
[B] You invoked interrupt(), explicitly. I assume it wasn't because the cat strolled on the keyboard :) - You had some intent by doing it. So, what is the intent? Whatever you intended to happen, program it in the catch block. The usual options are either to abort a thread entirely (so, just return;), or if you have a loop that sleeps, checks something, sleeps again, etc - to recheck (a poor man's wait/notify setup, in other words), or to re-read some configuration or otherwise re-perform some initialization procedure. It's up to you. There is no described style or rule.
Does the method interrupt() do anything else other than resetting the interrupted flag?
Yes, it returns true or false depending on whether it was up or not. But this is completely pointless. Everything in java that can throw InterruptedException +lowers that flag first_. There is therefore absolutely no point whatsoever in lowering the flag in the catch block - it has already been lowered if you ever get there. You EITHER get the flag raised on you, OR you get an InterruptedException (the flag is there because not everything throws InterruptedEx). Note that if your thread is sleeping due to some sleeping op that is not declared to throws InterruptedException, then it may interrupt or not - it depends on the OS capabilities. For example, if you're waiting for network traffic (e.g. calling read() on an InputStream derived from a java.net.Socket or whatnot), then interrupted the thread may either do nothing at all other than raise the flag, or, it will actually end up shutting down the threadsleep. In that case, the code in that InputStream will lower the flag and ends up throwing some sort of IOException (because it can't throw InterruptedException; InterruptedException is checked, and read() doesn't declare it).
Note that if the flag is raised, and you invoke any method that is specced to throw InterruptedException, said method will act IMMEDIATELY, it never goes to sleep in the first place. It lowers the flag and throws InterruptedException, instantly.
Therefore you rarely need to check the flag - very few threads lack a looping construct and very few threads will chug on for a long time without ever invoking anything that will end up invoking Thread.sleep() or obj.wait() somewhere along the line.
NB: The intent of the interrupted() method is to use it as the sole condition in a busy loop that doesn't otherwise call any code that would throw InterruptedException. e.g.:
while (!Thread.interrupted()) {
doSomethingThatNeverSleeps();
}
that'd be the whole body of your run() method. That will keep running forever and make your CPU fans make the laptop take off, at least until some other code tells the thread to call it a day by invoking .interupt(). As I said, rare that you need this construct, but that's what it is for.

Why does Thread class has static methods when we have currentThread() method?

Thread class has many static methods that are called by class name. Some of them are:
But yet, we are provided with method currentThread() that returns currently executing thread object. Some are:
Unfortunately, this created confusion in my head. When I think of a method I want, I have no clue whether I would found it as static or instance. So why did they make such two approaches?
I mean, couldn't they all be grouped in same 'calling'? For example why is sleep() static and not instance method called with Thread.currentThread().sleep()? Another weird example is between interrupted() and isInterrupted() defined in different manner. They do exactly the same thing, just interrupted() additionally clears interrupted flag. Has anyone logic answer to this, so I have no struggle where to find each method?
It's tricky; the answer is different for each method. Let's go through the ones you named:
Thread.sleep
Imagine I called: someOtherThread.sleep(1000L);. What would this mean? Surely that ought to mean: Sleep that other thread, not my thread. Except that's not something java offers: You can sleep your own thread, but you cannot arbitrarily tell some other thread to freeze like they're doing a mime act, mid execution of some arbitrary command. For example, if that thread is currently blocked on, say, waiting for the OS to deliver some bytes from a file read, that definitely cannot just fall asleep, and there are many, many other scenarios where a thread cannot do that.
Thus, java does not offer this functionality - you can't sleep other threads. Only your own. There are two different ways to make this at least somewhat clear in API design:
The first is to have sleep be an instance method (thus, you'd have to write e.g. Thread.currentThread().sleep(1000L);), and spec the method that it will guaranteed, always, immediately throw an IllegalStateException if you invoke it on any thread except your own. This means a compile/write-time detectable error condition would only be caught at runtime (this is bad; catching a problem earlier is obviously better than catching it later), it makes the code you'd have to write to sleep needlessly longer, and the existence of a sleep method you can invoke on thread instances sure suggests that you can sleep other threads. It'd just be crappy API design.
The second is to make sleep static.
Think of it this way: java.lang.Thread is a container for two mostly unrelated batches of methods: One is a set of methods you can use on threads (those'd be the instance methods). The other is a bunch of thread and flow related primitives, such as 'sleep', 'yield', and interrupt interaction. They just happen to be shoved into the same class.
interrupt
This is probably the trickiest. Unlike sleeping, you can in fact ask another thread's interrupt flag status.
The reason there are two methods are because of the more or less intended API design of the interrupt system.
The interrupt system is designed as follows:
If you want some thread to stop what it is doing for some unspecified reason (for example, you want it to re-check some condition, or just cease running, or anything else you can think of) then you need a mechanism to signal this. In particular, you'd want such a mechanism to ensure that any interruptable blocking operations, such as Thread.sleep(100000L) are interrupted. In other words, you can't just say: Whatever, it's up to the code itself, just, um, make an AtomicBoolean and check it a lot.
That's where the 'interrupt' system comes in. The idea is:
To interrupt any thread, raise its interrupt flag, with thatThread.interrupt();
All methods that do interruptable things should check this flag. The procedure is: If it is raised, then [A] clear it, and [B] handle the interruption, doing whatever the programmer intended to happen upon interruption (just stop running, or re-check some condition, re-read some config file, who knows - it's programming, whatever you want it to mean). If you CAN handle the notion of aborting some operation, but you CANNOT handle it, then instead clear that flag and throw InterruptedException, so that the caller can handle it.
As a result, any code that knows what 'I was interrupted!' means should BOTH check the flag (especially if that code has an event loop, which most thread-based code does have), AND catch InterruptedException from any method specced to throw it, and react in the exact same way to either catching that exception or having Thread.interrupted() return true.
Things go all sorts of wrong if you handle the fact that the interrupt flag is up, but you do NOT lower it. For example, if you abort your CPU-bound bitcoin mining or whatnot and just return back to your caller whilst leaving the flag up, then the next time caller invokes Thread.sleep, thread.sleep will notice the flag is up and IMMEDIATELY exit, not sleeping at all (exit by throwing InterruptedException, to be specific). That isn't intended. Hence why it is important that if you respond to an interrupt, you lower that flag.
So, let's go back to API design. There are two strategies:
Hypothetical design A
while (!Thread.currentThread().isInterrupted()) {
mineAnotherBitCoin();
}
Thread.currentThread().clearInterruptFlag();
Design B
while (!Thread.checkAndClearInterruptFlag()) {
mineAnotherBitCoin();
}
Note how design B is conceptually a lot shorter, does not have a 'gap' between checking the flag and clearing it, and therefore is fundamentally less error prone. Furthermore, for, well, reasons, it has been decided that raising an interrupt flag is something you can do to other threads (there is no point interrupting yourself, after all), but clearing one is a thing you can only do to your own thread.
B is what java actually has, except the method is somewhat strangely named interrupted(), and not checkAndClearInterruptFlag(). If you want an explanation of why some methods in java are somewhat suspectly named, it's because java does not like breaking backwards compatibility.
Fundamentally then, while they sound real similar, isInterrupted() and interrupted() do two very different things.
isInterrupted() is to check if some thread has already been interrupted and its response to this interruption is still pending (nothing has yet handled it).
interrupted() is something you put in the condition in your while loops that define the core body of your thread implementation (your 'event loop').
*) It doesn't help that the vast majority of examples of how to make threads in java are erroneous in that they don't properly do this. They tend to be while (true) or while (!running) {} or similar, either ignoring interruptions entirely or with a handrolled interrupt-esque 'running' concept.
So how do I know where to look?
Simple enough: If it's a thing that conceptually doesn't belong to any particular thread (such as 'how many threads are active right now'), or it is a utility concept (such as 'sleep'), or it is a thing that from a VM design principle can only be done to your own thread and not to anything else, then it is a static method in Thread.
If it's a thing that does belong to a particular thread AND the VM would let you do it to other threads (such as interrupting it, asking for its name, id, or priority, getting a stack dump, freezing this thread until the other thread completes, or setting its priority), then it's an instance method.
In many ways you can reverse this logic: If you want to do some thread related business, check the Thread class for something that seems to describe what you want. Then check if the method is static or not. If it is static, you don't get to do it to any other thread (such as clearing the interrupt flag, or sleep). If it's instance, you CAN do that to other threads (such as changing its priority level).
Because you can't make another thread sleep that is not the thread you are on. Even when you call Thread.currentThread().sleep(), you are calling the static method 'sleep'. If you were to call the sleep method on a different Thread object, it would still make the current thread sleep.
If you want to make a different thread sleep, you should set a flag that the other thread reads, which causes it to sleep.

Why do InterruptedExceptions clear a thread's interrupted status?

If a thread is interrupted while inside Object.wait() or Thread.join(), it throws an InterruptedException, which resets the thread's interrupted status. I. e., if I have a loop like this inside a Runnable.run():
while (!this._workerThread.isInterrupted()) {
// do something
try {
synchronized (this) {
this.wait(this._waitPeriod);
}
} catch (InterruptedException e) {
if (!this._isStopping()) {
this._handleFault(e);
}
}
}
the thread will continue to run after calling interrupt(). This means I have to explicitly break out of the loop by checking for my own stop flag in the loop condition, rethrow the exception, or add a break.
Now, this is not exactly a problem, since this behaviour is well documented and doesn't prevent me from doing anything the way I want. However, I don't seem to understand the concept behind it: Why is a thread not considered interrupted anymore once the exception has been thrown? A similar behaviour also occurs if you get the interrupted status with interrupted() instead of isInterrupted(), then, too, the thread will only appear interrupted once.
Am I doing something unusual here? For example, is it more common to catch the InterruptedException outside the loop?
(Even though I'm not exactly a beginner, I tagged this "beginner", because it seems like a very basic question to me, looking at it.)
The idea is that an interrupt should be handled once. If an explicit InterruptedException did not clear the "interrupt" flag then most catchers for InterruptedException would have to explicitly clear that flag. Conversely, you can "unclear" the flag by self-interruption (Thread.currentThread().interrupt()). Java's designers went for the semantics which would save keystrokes most of the time (i.e. you more often want to clear the flag than keep it set).
It shouldn't. This is an unfortunate design flaw that makes relying on interruptions a risky business, as too often library code will catch InterruptedException without resetting the thread's interrupted flag and carry on. If you happen to signal an interruption to your thread when that particular piece of broken library code is running, when your code regains execution control, it'll be left without a clue that the interruption happened.
This only needs to happen once in any place that you're calling from your code, so in order to be able to interrupt a thread and then use the interrupted bit to control your flow from inside said thread safely, you need to be 100% sure that every piece of code that you're calling does not clear the interrupted bit by mistake. This is very hard to do when libraries are involved, but even if you could account for every single library that you're using in your code, that still doesn't account for buggy JRE code that can make the same mistake.
The fact that it only takes one library (or JRE!) author to not care or think about interruptions in order to break the logic of code that requires it shows that this is the wrong default action to take. Someone who doesn't care about the thread's interrupted bit probably won't bother to reset it after catching InterruptedException – maybe they don't even know it exists! If catching InterruptedException didn't reset the thread's interrupted status, then anyone who did not know about the interrupted bit would automatically "do the right thing" and not cause a problem for any calling code relying on interruptions. Anyone who required clearing it could still do so manually, but then it'd be an explicit action which is much more likely to be correct than an usually unintended side-effect of catching the checked InterruptedException exception. As it stands right now, if you rely on the thread's interrupted bit, anyone down your calling stack that calls Thread.sleep() carelessly can potentially ruin your day.
As a result, most Java multi-threaded code will just duplicate the Java thread interrupt model with an "isRunning" instance field and some mechanism to flip it as a workaround.
Write your code like this and you won't need a flag:
try {
while (!this._workerThread.isInterrupted()) {
// do something
synchronized (this) {
this.wait(this._waitPeriod);
}
// do something else
}
} catch (InterruptedException e) {
// ignore ...
}
As #Boyan points out, it is a bad idea to squash that the interrupt exception ... in general. In this case, the context will determine whether you should squash it (as above), set the interrupt flag (again) or allow the exception to propagate. Among other things, it depends on what the interrupt means in / to your application.
That's because an InterruptedException is considered an abnormal event in which someone else tries to stop a thread from outside it.
When you want to really interrupt a thread you just break its loop condition by setting a boolean or something similar. Or you use .wait() and .notify() from inside that thread. But if you are doing wait() externally:
an exception is thrown to notify that an external thread tried to interrupt me or to make me wait
the thread continues its work because it doesn't take any order from another thread! But the raise of the exception allows you to add special handling and do whatever you want, also effectively stop the thread.

Who is calling the Java Thread interrupt() method if I'm not?

I've read and re-read Java Concurrency in Practice, I've read several threads here on the subject, I've read the IBM article Dealing with InterruptedException and yet there's something I'm simply not grasping which I think can be broken down into two questions:
If I'm never ever interrupting other threads myself, what can trigger an InterruptedException?
If I'm never ever interrupting other threads myself using interrupt() (say because I'm using other means to cancel my working threads, like poison pills and while (!cancelled) style loop [as both explained in JCIP]), what does an InterruptedException then mean? What am I supposed to do upon catching one? Shutdown my app?
The Thread interrupt mechanism is the preferred way to get a (cooperating) thread to respond a request to stop what it is doing. Any thread (including the thread itself I think) could call interrupt() on a Thread.
In practice, the normal use-cases for interrupt() involve some kind of framework or manager telling some worker thread to stop what they are doing. If the worker thread is "interrupt aware" it will notice that it has been interrupted via an exception, or by periodically checking its interrupted flag. On noticing that it has been interrupted, a well-behaved thread would abandon what it is doing and end itself.
Assuming the above use-case, your code is likely to be interrupted if it is run within a Java framework or from some worker thread. And when it is interrupted, your code should abandon what it is doing and cause itself to end by the most appropriate means. Depending on how your code was called, this might be done by returning or by throwing some appropriate exception. But it probably should not call System.exit(). (Your application does not necessarily know why it was interrupted, and it certainly does not know if there are other threads that need to be interrupted by the framework.)
On the other hand, if your code is not designed to run under the control of some framework, you could argue that the InterruptedException is an unexpected exception; i.e. a bug. In that case, you should treat the exception as you would other bugs; e.g. wrap it in an unchecked exception, and catch and log it at the same point you deal with other unexpected unchecked exceptions. (Alternatively, your application could simply ignore the interrupt and continue doing what it was doing.)
1) If I'm never ever interrupting other threads myself, what can trigger an InterruptedException?
One example is if your Runnable objects are executed using an ExecutorService and shutdownNow() is called on the service. And in theory, any 3rd-party thread pool or thread management framework could legitimately do something like this.
2) If I'm never ever interrupting other threads myself using interrupt() ... what does an InterruptedException then mean? What am I supposed to do upon catching one? Shutdown my app?
You need analyze the codebase to figure out what is making the interrupt() calls and why. Once you have figured that out, you can work out what >>your<< part of the app needs to do.
Until you know why InterruptedException is being thrown, I would advise treating it as a hard error; e.g. print a stacktrace to the log file and shut down the app. (Obviously, that's not always the right answer ... but the point is that this is "a bug", and it needs to be brought to the attention of the developer / maintainer.)
3) How do I find out who / what is calling interrupt()?
There is no good answer to this. The best I can suggest is to set a breakpoint on the Thread.interrupt() and look at the call stack.
If you decide to integrate your code with other libraries, they can call interrupt() on your code. e.g. if you decide in the future to execute your code within an ExecutorService, then that may force a shutdown via interrupt().
To put it briefly, I would consider not just where your code is running now, but in what context it may run in the future. e.g. are you going to put it in a library ? A container ? How will other people use it ? Are you going to reuse it ?
As others have pointed out, interrupting a thread (actually, interrupting a blocking call) is usually used for purposes of exiting cleanly or cancelling an ongoing activity.
However, you should not treat an InterruptedException alone as a "quit command". Instead, you should think of interrupts as a means to control the running status of threads, much in the same way as Object.notify() does. In the same way that you'd check the current state after waking up from a call to Object.wait() (you don't assume that the wakeup means your wait condition has been satisfied), after being nudged with an interrupt you should check why you were interrupted. There is usually a way to do this. For example, java.util.concurrent.FutureTask has an isCancelled() method.
Code sample:
public void run() {
....
try {
.... // Calls that may block.
} catch (InterruptedException e) {
if (!running) { // Add preferred synchronization here.
return; // Explicit flag says we should stop running.
}
// We were interrupted, but the flag says we're still running.
// It would be wrong to always exit here. The interrupt 'nudge'
// could mean something completely different. For example, it
// could be that the thread was blocking on a read from a particular
// file, and now we should read from a different file.
// Interrupt != quit (not necessarily).
}
....
}
public void stop() {
running = false; // Add preferred synchronization here.
myThread.interrupt();
}
The problem with the question is "I". "I" usually refers to a single instance of a class. I mean by that, that any particular piece of low-level code (class) should not rely upon the implementation of the entire system. Having said that you do have make some "architectural" decisions (like what platform to run on).
Possible unexpected interrupts coming from the JRE are canceled tasks in java.util.concurrent and shutting down applets.
Handling of thread interrupts is usually written incorrectly. Therefore, I suggest the architectural decision to avoid causing interrupts where possible. However, code handling interrupts should always be written correctly. Can't take interrupts out of the platform now.
You could learn this by creating your own thread class (extending java.lang.Thread) and overriding interrupt() method, in which you record the stacktrace into, say, a String field, and then transfer to super.interrupt().
public class MyThread extends Thread {
public volatile String interruptStacktrace; // Temporary field for debugging purpose.
#Override
public void interrupt() {
interruptStacktrace = dumpStack(); // You implement it somehow...
super.interrupt();
}
}
As already mentioned, another library can interrupt your threads. Even if the library doesn't have explicit access to the threads from your code, they can still get the list of threads that are running and interrupt them that way with the following method.
I think I understand why you are a bit confused about interruption. Please consider my answers in line:
If I'm never ever interrupting other threads myself, what can trigger an InterruptedException?
Firstly you may interrupt other threads; I know that in JCiP it is mentioned that you should never interrupt threads you do not own; however, this statement has to be properly understood. What it means is that your code which might be running in any arbitrary thread should not handle interruption because since it is not the owner of the thread it has no clue of its interruption policy. So you may request interruption on other threads, but let its owner take the course of interruption action; it has the interruption policy encapsulated within it, not your task code; at least be courteous to set the interruption flag!
There are many ways why there could be interruptions still, may be timeouts, JVM interrupts etc.
If I'm never ever interrupting other threads myself using interrupt() (say because I'm using other means to cancel my working threads, like poison pills and while (!cancelled) style loop [as both explained in JCIP]), what does an InterruptedException then mean? What am I supposed to do upon catching one? Shutdown my app?
You need to be very careful here; if you own the thread which threw InterruptedException (IE), then you know what to do upon catching it, say you may shutdown your app/service or you may replace this killed thread with a new one! However, if you do not own the thread then upon catching IE either rethrow it higher up the call stack or after doing something (may be logging), reset the interrupted status so that the code which owns this thread, when control reaches it, may learn that the thread was interrupted and hence take actions as it will since only it knows the interruption policy.
Hope this helped.
The InterruptedException says that a routine may be interrupted, but not necessarily that it will be.
If you don't expect the interrupt then you should treat it as you might any other unexpected exception. If it's in a critical section where an unexpected exception could have heinous consequences, it might be best to try and clean up resources and gracefully shutdown (because getting the interrupt signals that your well-engineered application that doesn't rely on interrupts is being used in a way it wasn't designed, and so there must be something wrong). Alternatively, if the code in question is something non-critical or trivial, you might want to ignore (or log) the interrupt and keep going.

Categories