Why invoke Thread.currentThread.interrupt() in a catch InterruptException block? - java

Why invoke the method Thread.currentThread.interrupt() in the catch block?

This is done to keep state.
When you catch the InterruptedException and swallow it, you essentially prevent any higher-level methods/thread groups from noticing the interrupt. Which may cause problems.
By calling Thread.currentThread().interrupt(), you set the interrupt flag of the thread, so higher-level interrupt handlers will notice it and can handle it appropriately.
Java Concurrency in Practice discusses this in more detail in Chapter 7.1.3: Responding to Interruption. Its rule is:
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.

I think this code sample makes things a bit clear.
The class which does the job :
public class InterruptedSleepingRunner implements Runnable {
#Override
public void run() {
doAPseudoHeavyWeightJob();
}
private void doAPseudoHeavyWeightJob() {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
// You are kidding me
System.out.println(i + " " + i * 2);
// Let me sleep <evil grin>
if (Thread.currentThread().isInterrupted()) {
System.out.println("Thread interrupted\n Exiting...");
break;
} else {
sleepBabySleep();
}
}
}
protected void sleepBabySleep() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
The Main class:
public class InterruptedSleepingThreadMain {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new InterruptedSleepingRunner());
thread.start();
// Giving 10 seconds to finish the job.
Thread.sleep(10000);
// Let me interrupt
thread.interrupt();
}
}
Try calling interrupt without setting the status back.

Note:
http://download.oracle.com/javase/7/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html
How do I stop a thread that waits for long periods (e.g., for input)?
For this technique to work, it's critical that any method that catches an interrupt exception and is not prepared to deal with it immediately reasserts the exception. We say reasserts rather than rethrows, because it is not always possible to rethrow the exception. If the method that catches the InterruptedException is not declared to throw this (checked) exception, then it should "reinterrupt itself" with the following incantation:
Thread.currentThread().interrupt();
This ensures that the Thread will reraise the InterruptedException as soon as it is able.

I would consider it a bad practice or at least a bit risky.
Usually higher level methods do not perform blocking operations and they will never see InterruptedException there. If you mask it in every place you perform interruptible operation, you will never get it.
The only rationale for Thread.currentThread.interrupt() and not raising any other exception or signaling interrupt request in any other way (e.g. setting interrupted local variable variable in a thread's main loop) is the situation where you really can't do anything with the exception, like in the finally blocks.
See Péter Török's answer, if you want to better understand implications of the Thread.currentThread.interrupt() call.

Refer from java doc
If this thread is blocked in an invocation of the wait(), join(),
sleep(long), then its interrupt status will be cleared and it will
receive an InterruptedException.
If this thread is blocked in an I/O operation, 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.
If none of the previous conditions hold then this thread's interrupt
status will be set.
So, if you change the sleepBabySleep() method in #Ajay George Answer to I/O operation or just a sysout, you don't have to set the status back to stop the program. (BTW, they don't even throw InterruptedException)
Just like #Péter Török said => This is done to keep state. (And particular for method that will throw InterruptedException)

Related

Stop a method in java

I have made a method to send an e-mail, and I wanted to try if it was possible to call a method inside the method itself with a timer, to do like a scheduler
public void createExcel(){
int year = Calendar.getInstance().get(Calendar.YEAR);
int num_week = data.getCurrentWeek()-1;
ArrayList<DHDemande> ListeDemandes = d.getDemandesForPaie(num_week, year);
try {
data.createFile(ListeDemandes);
Thread.sleep(20000);
createExcel();
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
But now the method doesn't stop (it was obvious) but even if I refresh Apache and if I change the method. How can I stop it ? because I receive an email every 20 second now
The thing with Treads is that there is now save way to tell it to just stop without memory leaks. You can use thread.stop(), this will kill the thread but it may cause memory problems if your objects are too big.
Quote from java doc:
stop() Deprecated. This method is inherently unsafe. Stopping a
thread with Thread.stop causes it to unlock all of the monitors that
it has locked (as a natural consequence of the unchecked ThreadDeath
exception propagating up the stack). If any of the objects previously
protected by these monitors were in an inconsistent state, the damaged
objects become visible to other threads, potentially resulting in
arbitrary behavior. Many uses of stop should be replaced by code that
simply modifies some variable to indicate that the target thread
should stop running. The target thread should check this variable
regularly, and return from its run method in an orderly fashion if the
variable indicates that it is to stop running. If the target thread
waits for long periods (on a condition variable, for example), the
interrupt method should be used to interrupt the wait. For more
information, see Why are Thread.stop, Thread.suspend and Thread.resume
Deprecated?.
Explore the Thread api and see if you can find anything else that suites your needs.
As Borislav mentioned, stop() is incorrect here, you need to call and handle interrupt().
class Test
{
public static Thread helloWorldLater()
{
Thread t = new Thread(new Runnable(){
#Override public void run()
{
try {
Thread.sleep(200);
System.out.println("Hello World");
}
catch(InterruptedException ex)
{
// clean up here
return;
}
}
});
t.start();
return t;
}
public static void main(String[] args) throws InterruptedException
{
Thread t = helloWorldLater();
Thread.sleep(100);
t.interrupt();
// no "Hello World" to be seen
}
}
Alternatively, depending on your Java version, you can also use the more modern concurrency Java APIs.
Besides Borislavs and Konrads legitimate comments on thread.stop(), you are calling the createExcel() method recursively (after Thread.sleep(20000)), so obviously your method will run forever. If you remove that call it should work like you expect it.

When would this catch block be reached?

I've used Thread.sleep for all kinds of different reasons, but one thing I've never understood is when an exception would occur during this try /catch block:
try {
Thread.sleep(1000); // sleep for 1 second.
} catch (Exception x) {
fail("Failed due to an exception during Thread.sleep!");
x.printStackTrace();
}
What would have to occur within the computer to actually hit an exception on Thread.sleep? My best guess, would be that maybe the system clock has a once in a lifetime "skip of a beat" like a heartbeat, but how often does this happen..
So in essence, my question is: When executing Thread.sleep, what would have to occur internally for #sleep to throw an exception?
If you look in the JavaDoc for Thread.sleep() you see exactly what might happen:
Throws:
IllegalArgumentException - if the value of millis is negative
InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.
An example on how to interrupt another thread might look like this:
public class Foo {
public static void main(final String[] args) throws Exception {
Thread sleepThread = new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Interrupted!");
}
}
});
sleepThread.start();
Thread.sleep(500);
sleepThread.interrupt();
}
}
This will print
Interrupted!
The Thread class defines an interrupt method. When it's called (obviously from another thread) by a thread and there's no security exception, an InterruptedException is thrown.
The purpose is, precisely (and normally), to interrupt the sleep.
Thread.sleep(someValue) can fire InterruptedException.
More info about handling this exception and reson for this you can find here.
You can find a lot usefull answers on SO. Here is the one for example:
When does Java's Thread.sleep throw InterruptedException?
When a thread interrupt is issued, for example if a signal was sent to shut the JVM down.
The Thread can throw an InterruptedException (which you should use instead of general Exception) when the Thread is interrupted (usually by the interrupt() method called from another Thread) instead of just waiting. It has nothing to do with the sleep() method.

Determine thread status with join and InterruptedException?

Seems to be that this method is takes in an array of threads, then determines if they have completed using InterruptedException, which seems plausible to me.
private static void waitUntilAllThreadsFinished(Thread[] threadArr) {
for(int i=0; i<threadArr.length; i++) {
try {
threadArr[i].join();
} catch (InterruptedException e) { }
log.debug("thread ["+threadArr[i].getName()+"] have completed");
}
}
If you just want to know if the thread has been interrupted , the use public boolean isInterrupted() method on the thread reference. This code is trying to block the current thread on each of the thread's completion, and retrying if it got interrupted in th meanwhile.
I think getState is more appropriate
I would not force the throw and catch, since it is not free of cost. The Thread class have methods to access the current state of an instance.
This code does not just determine whether all threads have completed, but waits for all of them to complete. And it's not using InterruptedException to do this. If join() calls on finished (dead) thread, the code just continues on without exception.
But it will work, I guess...

Why restore interrupt flag of a task that ran in a thread pool's thread

This snippet is from JCIP (Brian Goetz) listing 6.15
f.get() throws InterruptedException and ExecutionException. Now, these exceptions are specific to the future correct?
Meaning the specific task represented by the future was interrupted or had an internal exception.
Questions -
Why do I need to restore the interrupt using "Thread.currentThread().interrupt()"? , because isnt the interrupt flag for the thread my task ran in? This is a little confusing.
Why throw launderThrowable exception? If one of the downloadImage had an issue, shouldnt we just process the other downloaded images intead of throwing from here and thus just "not" processing the remaining futures?
package net.jcip.examples;
import java.util.*;
import java.util.concurrent.*;
import static net.jcip.examples.LaunderThrowable.launderThrowable;
/**
* Renderer
* <p/>
* Using CompletionService to render page elements as they become available
*
* #author Brian Goetz and Tim Peierls
*/
public abstract class Renderer {
private final ExecutorService executor;
Renderer(ExecutorService executor) {
this.executor = executor;
}
void renderPage(CharSequence source) {
final List<ImageInfo> info = scanForImageInfo(source);
CompletionService<ImageData> completionService =
new ExecutorCompletionService<ImageData>(executor);
for (final ImageInfo imageInfo : info)
completionService.submit(new Callable<ImageData>() {
public ImageData call() {
return imageInfo.downloadImage();
}
});
renderText(source);
try {
for (int t = 0, n = info.size(); t < n; t++) {
Future<ImageData> f = completionService.take();
ImageData imageData = f.get();
renderImage(imageData);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
throw launderThrowable(e.getCause());
}
}
interface ImageData {
}
interface ImageInfo {
ImageData downloadImage();
}
abstract void renderText(CharSequence s);
abstract List<ImageInfo> scanForImageInfo(CharSequence s);
abstract void renderImage(ImageData i);
}
When you catch InterruptedException interrupted flag gets reset and your thread is technically not interrupted anymore. However, you don't know if the code that called your code (or other code in the same thread), requires any additional interrupt handling. By calling interrupt() you raise the flag again and effectively saying to the rest of the application "This thread is still interrupted - act on it if necessary".
Consider example. You method is called from the loop that must terminate if thread is interrupted. You caught the exception and if you don't raise the flag, the loop will not terminate as required.
By catching InterruptedException, you are stopping the interruption from reaching the Thread in which you are running. But you want it to reach it, in case there is any special processing the Thread needs to do in case of interruption - you can't tell, so you'd better play it safe and allow it to percolate up. You may do some processing yourself (to clean up, exit what you are doing, etc), but you must pass it on. The best way to do this is to call Thread.currentThread().interrupt().
The interruption does not necessarily happen on the thread pool's thread. The interruption is for a point when your current thread is interrupted while you are waiting on the future's get to complete. For instance, if you made the Future accessible to another part of the program that can cancel the download, then Future.cancel(true) will cause that InterruptedException to occur which you can then clean up the rest of the data. And as Beohemaian mentioned, it is always safe to propogate the interruption.
Thats a good question. I think that was more of a design choice of what he wanted it to do. But you can easily hold onto that error and throw it after the rest complete. Something to think about though, what if its an OutOfMemoryError? Then the launder would be useful to only throw if its an Error and maybe not a RuntimeException.

is there a 'block until condition becomes true' function in java?

I'm writing a listener thread for a server, and at the moment I'm using:
while (true){
try {
if (condition){
//do something
condition=false;
}
sleep(1000);
} catch (InterruptedException ex){
Logger.getLogger(server.class.getName()).log(Level.SEVERE, null, ex);
}
}
With the code above, I'm running into issues with the run function eating all the cpu time looping. The sleep function works, but it seems be a makeshift fix, not a solution.
Is there some function which would block until the variable 'condition' became 'true'?
Or is continual looping the standard method of waiting until a variable's value changes?
Polling like this is definitely the least preferred solution.
I assume that you have another thread that will do something to make the condition true. There are several ways to synchronize threads. The easiest one in your case would be a notification via an Object:
Main thread:
synchronized(syncObject) {
try {
// Calling wait() will block this thread until another thread
// calls notify() on the object.
syncObject.wait();
} catch (InterruptedException e) {
// Happens if someone interrupts your thread.
}
}
Other thread:
// Do something
// If the condition is true, do the following:
synchronized(syncObject) {
syncObject.notify();
}
syncObject itself can be a simple Object.
There are many other ways of inter-thread communication, but which one to use depends on what precisely you're doing.
EboMike's answer and Toby's answer are both on the right track, but they both contain a fatal flaw. The flaw is called lost notification.
The problem is, if a thread calls foo.notify(), it will not do anything at all unless some other thread is already sleeping in a foo.wait() call. The object, foo, does not remember that it was notified.
There's a reason why you aren't allowed to call foo.wait() or foo.notify() unless the thread is synchronized on foo. It's because the only way to avoid lost notification is to protect the condition with a mutex. When it's done right, it looks like this:
Consumer thread:
try {
synchronized(foo) {
while(! conditionIsTrue()) {
foo.wait();
}
doSomethingThatRequiresConditionToBeTrue();
}
} catch (InterruptedException e) {
handleInterruption();
}
Producer thread:
synchronized(foo) {
doSomethingThatMakesConditionTrue();
foo.notify();
}
The code that changes the condition and the code that checks the condition is all synchronized on the same object, and the consumer thread explicitly tests the condition before it waits. There is no way for the consumer to miss the notification and end up stuck forever in a wait() call when the condition is already true.
Also note that the wait() is in a loop. That's because, in the general case, by the time the consumer re-acquires the foo lock and wakes up, some other thread might have made the condition false again. Even if that's not possible in your program, what is possible, in some operating systems, is for foo.wait() to return even when foo.notify() has not been called. That's called a spurious wakeup, and it is allowed to happen because it makes wait/notify easier to implement on certain operating systems.
As nobody published a solution with CountDownLatch. What about:
public class Lockeable {
private final CountDownLatch countDownLatch = new CountDownLatch(1);
public void doAfterEvent(){
countDownLatch.await();
doSomething();
}
public void reportDetonatingEvent(){
countDownLatch.countDown();
}
}
Similar to EboMike's answer you can use a mechanism similar to wait/notify/notifyAll but geared up for using a Lock.
For example,
public void doSomething() throws InterruptedException {
lock.lock();
try {
condition.await(); // releases lock and waits until doSomethingElse is called
} finally {
lock.unlock();
}
}
public void doSomethingElse() {
lock.lock();
try {
condition.signal();
} finally {
lock.unlock();
}
}
Where you'll wait for some condition which is notified by another thread (in this case calling doSomethingElse), at that point, the first thread will continue...
Using Locks over intrinsic synchronisation has lots of advantages but I just prefer having an explicit Condition object to represent the condition (you can have more than one which is a nice touch for things like producer-consumer).
Also, I can't help but notice how you deal with the interrupted exception in your example. You probably shouldn't consume the exception like this, instead reset the interrupt status flag using Thread.currentThread().interrupt.
This because if the exception is thrown, the interrupt status flag will have been reset (it's saying "I no longer remember being interrupted, I won't be able to tell anyone else that I have been if they ask") and another process may rely on this question. The example being that something else has implemented an interruption policy based on this... phew. A further example might be that your interruption policy, rather that while(true) might have been implemented as while(!Thread.currentThread().isInterrupted() (which will also make your code be more... socially considerate).
So, in summary, using Condition is rougly equivalent to using wait/notify/notifyAll when you want to use a Lock, logging is evil and swallowing InterruptedException is naughty ;)
You could use a semaphore.
While the condition is not met, another thread acquires the semaphore.
Your thread would try to acquire it with acquireUninterruptibly()
or tryAcquire(int permits, long timeout, TimeUnit unit) and would be blocked.
When the condition is met, the semaphore is also released and your thread would acquire it.
You could also try using a SynchronousQueue or a CountDownLatch.
Lock-free solution(?)
I had the same issue, but I wanted a solution that didn't use locks.
Problem: I have at most one thread consuming from a queue. Multiple producer threads are constantly inserting into the queue and need to notify the consumer if it's waiting. The queue is lock-free so using locks for notification causes unnecessary blocking in producer threads. Each producer thread needs to acquire the lock before it can notify the waiting consumer. I believe I came up with a lock-free solution using LockSupport and AtomicReferenceFieldUpdater. If a lock-free barrier exists within the JDK, I couldn't find it. Both CyclicBarrier and CoundDownLatch use locks internally from what I could find.
This is my slightly abbreviated code. Just to be clear, this code will only allow one thread to wait at a time. It could be modified to allow for multiple awaiters/consumers by using some type of atomic collection to store multiple owner (a ConcurrentMap may work).
I have used this code and it seems to work. I have not tested it extensively. I suggest you read the documentation for LockSupport before use.
/* I release this code into the public domain.
* http://unlicense.org/UNLICENSE
*/
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.concurrent.locks.LockSupport;
/**
* A simple barrier for awaiting a signal.
* Only one thread at a time may await the signal.
*/
public class SignalBarrier {
/**
* The Thread that is currently awaiting the signal.
* !!! Don't call this directly !!!
*/
#SuppressWarnings("unused")
private volatile Thread _owner;
/** Used to update the owner atomically */
private static final AtomicReferenceFieldUpdater<SignalBarrier, Thread> ownerAccess =
AtomicReferenceFieldUpdater.newUpdater(SignalBarrier.class, Thread.class, "_owner");
/** Create a new SignalBarrier without an owner. */
public SignalBarrier() {
_owner = null;
}
/**
* Signal the owner that the barrier is ready.
* This has no effect if the SignalBarrer is unowned.
*/
public void signal() {
// Remove the current owner of this barrier.
Thread t = ownerAccess.getAndSet(this, null);
// If the owner wasn't null, unpark it.
if (t != null) {
LockSupport.unpark(t);
}
}
/**
* Claim the SignalBarrier and block until signaled.
*
* #throws IllegalStateException If the SignalBarrier already has an owner.
* #throws InterruptedException If the thread is interrupted while waiting.
*/
public void await() throws InterruptedException {
// Get the thread that would like to await the signal.
Thread t = Thread.currentThread();
// If a thread is attempting to await, the current owner should be null.
if (!ownerAccess.compareAndSet(this, null, t)) {
throw new IllegalStateException("A second thread tried to acquire a signal barrier that is already owned.");
}
// The current thread has taken ownership of this barrier.
// Park the current thread until the signal. Record this
// signal barrier as the 'blocker'.
LockSupport.park(this);
// If a thread has called #signal() the owner should already be null.
// However the documentation for LockSupport.unpark makes it clear that
// threads can wake up for absolutely no reason. Do a compare and set
// to make sure we don't wipe out a new owner, keeping in mind that only
// thread should be awaiting at any given moment!
ownerAccess.compareAndSet(this, t, null);
// Check to see if we've been unparked because of a thread interrupt.
if (t.isInterrupted())
throw new InterruptedException();
}
/**
* Claim the SignalBarrier and block until signaled or the timeout expires.
*
* #throws IllegalStateException If the SignalBarrier already has an owner.
* #throws InterruptedException If the thread is interrupted while waiting.
*
* #param timeout The timeout duration in nanoseconds.
* #return The timeout minus the number of nanoseconds that passed while waiting.
*/
public long awaitNanos(long timeout) throws InterruptedException {
if (timeout <= 0)
return 0;
// Get the thread that would like to await the signal.
Thread t = Thread.currentThread();
// If a thread is attempting to await, the current owner should be null.
if (!ownerAccess.compareAndSet(this, null, t)) {
throw new IllegalStateException("A second thread tried to acquire a signal barrier is already owned.");
}
// The current thread owns this barrier.
// Park the current thread until the signal. Record this
// signal barrier as the 'blocker'.
// Time the park.
long start = System.nanoTime();
LockSupport.parkNanos(this, timeout);
ownerAccess.compareAndSet(this, t, null);
long stop = System.nanoTime();
// Check to see if we've been unparked because of a thread interrupt.
if (t.isInterrupted())
throw new InterruptedException();
// Return the number of nanoseconds left in the timeout after what we
// just waited.
return Math.max(timeout - stop + start, 0L);
}
}
To give a vague example of usage, I'll adopt james large's example:
SignalBarrier barrier = new SignalBarrier();
Consumer thread (singular, not plural!):
try {
while(!conditionIsTrue()) {
barrier.await();
}
doSomethingThatRequiresConditionToBeTrue();
} catch (InterruptedException e) {
handleInterruption();
}
Producer thread(s):
doSomethingThatMakesConditionTrue();
barrier.signal();
One could also leverage CompletableFutures (since Java 8):
final CompletableFuture<String> question = new CompletableFuture<>();
// from within the consumer thread:
final String answer = question.get(); // or: event.get(7500000, TimeUnit.YEARS)
// from within the producer thread:
question.complete("42");

Categories

Resources