Can a synchronized block/method be interrupted? - java

While I know the theoretical differences between Re-EntrantLocks and synchronized, I'm confused to the below point.
See this statement from an article on Javarevisited comparing synchronized and Lock objects:
One more worth noting difference between ReentrantLock and
synchronized keyword in Java is, ability to interrupt Thread while
waiting for Lock. In case of synchronized keyword, a thread can be
blocked waiting for lock, for an indefinite period of time and there
was no way to control that. ReentrantLock provides a method called
lockInterruptibly(), which can be used to interrupt thread when it is
waiting for lock. Similarly tryLock() with timeout can be used to
timeout if lock is not available in certain time period.
As per the above statement, I did try interrupting the Thread waiting() on synchronized method (i.e blocking wait) and it did throw an InterruptedException. But this behavior is contradictory with what is stated in the above statement.
// this method is called from inside run() method of every thread.
public synchronized int getCount() {
count++;
try {
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName() + " gets " + count);
} catch (InterruptedException e) {
e.printStackTrace();
}
return count;
}
....
....
t1.start();
t2.start();
t3.start();
t4.start();
t2.interrupt();
Here is the output that I got :
Thread 1 gets 1
Thread 4 gets 2
Thread 3 gets 3
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at locks.SynchronizedLockInterrupt.getCount(SynchronizedLockInterrupt.java:10)
at locks.SynchronizedLockInterrupt$2.run(SynchronizedLockInterrupt.java:35)
at java.lang.Thread.run(Unknown Source)
I'm confused if my example is not correct or the quoted statement about synchronized() is incorrect?

Without the rest of the code this question might not be fully answered.
What, I think, you're being confused with here is that you're seeing that, whilst the code would imply you cannot "interrupt" a thread that's blocked on a synchronized lock you are seeing that your count variable seems to be unaffected by the thread which is supposed to have entered into this method.
Important to note that you can technically "interrupt" a blocked thread, as in you can call interrupt() on it and this will set the interrupted flag. Just because a Thread has the interrupted flag set does not mean that it cannot execute any more code. Simply, when it get's to the next code that checks for an interrupted state, that code will likely throw an InterruptedException whilst clearing the flag at the same time. If the person catching the exception intends to do more work, it's their (almost moral) duty to re-set the flag or throw the same.
So, yes, in your example, you are catching the exception that has been thrown by .sleep() on entry, likely before the thread was sleep-ed, you then print the stack trace that proves that.
The outstanding question that might be causing confusion for you; why, then, did my count not increment if this code was allowed to run until the .sleep() method call?
The answer is that the count variable was incremented, you just didn't see the result.
synchronized in Java does not guarantee order and can lead to starvation so t2 just happened to be executed last and you never checked the count before you slept to see that it was already 3
So to answer your question, the documentation is correct and the behaviour is correct.
Interrupting a thread which is waiting "uninterruptedly" on a Lock , ReentrantLock or synchronized block will merely result in the thread waking up and seeing if it's allowed to take the lock yet, by whatever mechanism is in place in the defining lock, and if it cannot it parks again until it is interrupted again or told it can take the lock. When the thread can proceed it simply proceeds with its interrupted flag set.
Contrast to lockInterruptibly where, actually, if you are interrupted, you do not ever get the lock, and instead you "abort" trying to get the lock and the lock request is cancelled.
lock and lockInterruptibly can be mixed use on the same ReentrantLock as the lock will manage the queue and skip requests that were CANCELLED by a finally statement because they were interrupted when waiting on a lock.
In summary:
You can almost always interrupt a thread.
The interrupt flag is usually only cleared on a thread by code that documents that it clears the flag when throwing the InterruptedException , but not all code documents this (lockInterruptibly on ReentrantLock does, but not the same on AbstractQueuedSynchronizer which powers the lock).
Interrupting a thread has different behaviour depending on what it is doing at the time;
A parked thread will be un-parked and have it's flag set, usually then cleared
A thread waiting on a lock / synchronized block will eventually get into the code but with interrupted flag set
A thread waiting on a lockInterruptibly or a get on a future etc will be unparked and behave as documented, aborting the lock acquisition.

synchronized is an intrinsic lock which is beyond the control of JDK.
Synchronization is built around an internal entity known as the intrinsic lock or monitor lock. (The API specification often refers to this entity simply as a "monitor.") Intrinsic locks play a role in both aspects of synchronization: enforcing exclusive access to an object's state and establishing happens-before relationships that are essential to visibility.
When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.
In your example, you are actually interrupting the sleep as JDK doc mentions.
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.
More details about how interrupt() works.
Many methods that throw InterruptedException, such as sleep, are designed to cancel their current operation and return immediately when an interrupt is received.

If have added a simple example to make it clear.
In your example you have already aquired the lock, see your stacktrace.
The code is self explaining.
The problem with synchronized is that it is no interruption point, whereas lock.lockInterruptibly() is. Note that lock.lock() is also not an interruption point.
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Foo {
public static void main(String[] args) throws InterruptedException {
// for the example with synchronized
Object monitor = new Object();
// for the example with locks
Lock lock = new ReentrantLock();
// iam lazy, just use both lock and motitor for this example
Thread one = new Thread(() -> {
lock.lock();
try {
synchronized (monitor) {
System.out.println("Thread one entered monitor");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Thread one interrupted");
Thread.currentThread().interrupt();
}
}
} finally {
lock.unlock();
}
});
// uncomment to use the monitor object
// Thread two = new Thread(() -> {
// synchronized (monitor) {
// System.out.println("Thread two entered monitor");
// }
// });
Thread two = new Thread(() -> {
try {
lock.lockInterruptibly();
try {
System.out.println("Thread one entered lock");
} finally {
lock.unlock();
}
} catch (InterruptedException e) {
System.out.println("Thread two interrupted while waiting for lock");
Thread.currentThread().interrupt();
}
});
// start thread one
one.start();
// wait for the thread to start, too lazy to implement notifications
Thread.sleep(1000);
// start thread two
two.start();
// interrupting will wait until thread one finished
two.interrupt();
}
}

If you remove "Thread.sleep(3000)", your 'getCount()' method will not throw exception.
You can only interrupt a thread either in sleep or wait in case of Synchronised method

You're not interrupting the synchronization, you're interrupting the sleep().

Related

Why calling notify in Java requires holding the lock?

Thread thread = new Thread(() -> {
synchronized (this){
try {
this.wait();
System.out.println("Woke");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
thread.start();
TimeUnit.SECONDS.sleep(1);
this.notify();
When calling notify it says
java.lang.IllegalMonitorStateException: current thread is not owner
The typical usage of notify is that you call it and then you release the lock implicitly (by leaving the synchronized block) so that the waiting threads may re-acquire the lock.
But code above calls notify even before it has the lock, so other threads can just try to acquire the lock, why not? I think the holding the lock is not necessary.
I think the holding the lock is not necessary.
It is necessary because the javadoc for Object.notify() says it is necessary. It states:
"This method should only be called by a thread that is the owner of
this object's monitor. A thread becomes the owner of the object's
monitor in one of three ways:
By executing a synchronized instance method of that object.
By executing the body of a synchronized statement that synchronizes on the object.
For objects of type Class, by executing a synchronized static method of that class."
But your real question is why is it necessary? Why did they design it this way?
To answer that, we need to understand that Java's wait / notify mechanism is primarily designed for implementing condition variables. The purpose of a condition variable is to allow one thread to wait for a condition to become true and for another thread to notify it that this has occurred. The basic pattern for implementing condition variables using wait() / notify() is as follows:
// Shared lock that provides mutual exclusion for 'theCondition'.
final Object lock = new Object();
// Thread #1
synchronized (lock) {
// ...
while (! theCondition) { // One reason for this loop will
// become later ...
lock.wait();
}
// HERE
}
// Thread # 2
synchronized (lock) {
// ...
if (theCondition) {
lock.notify();
}
}
This when thread #1 reaches // HERE, it knows that theCondition is now true. Furthermore it is guaranteed the current values variables that make up the condition, and any others controlled by the lock monitor will now be visible to thread #1.
But one of the prerequisites for this actually working is that both thread #1 and thread #2 are synchronized on the same monitor. That will guarantee the visibility of the values according to a happens before analysis based on the Java Memory Model (see JLS 17.4).
A second reason that the above needs synchronization is because thread #1 needs exclusive access to the variables to check the condition and then use them. Without mutual exclusion for the shared state between threads #1 and #2, race conditions are possible that can lead to a missed notification.
Since the above only works reliably when threads #1 and #2 hold the monitor when calling wait and notify, the Java designers decided to enforce this in implementations of the wait and notify methods themselves. Hence the javadoc that I quoted above.
Now ... your use-case for wait() / notify() is simpler. No information is shared between the two threads ... apart from the fact that the notify occurred. But it is still necessary to follow the pattern above.
Consider the consequences of this caveat in the javadoc for the wait() methods:
"A thread can wake up without being notified, interrupted, or timing out, a so-called "spurious wakeup". While this will rarely occur in practice, applications must guard against it ..."
So one issue is that a spurious wakeup could cause the child thread to be woken before the main thread's sleep(...) completes.
A second issue is that is the child thread is delayed, the main thread may notify the child before the child has reached the wait. The notification then be lost. (This might happen due to system load.)
What these issues mean is that your example is incorrect ... in theory, if not in reality. And in fact, it is not possible to solve your problem using wait / notify without following the pattern above/
A corrected version of your example (i.e. one that is not vulnerable to spurious wakeups, and race conditions) looks like this:
final Object lock = new Object;
boolean wakeUp = false;
Thread thread = new Thread(() -> {
synchronized (lock){
try {
while (!wakeUp) {
this.wait();
}
System.out.println("Woke");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
thread.start();
TimeUnit.SECONDS.sleep(1);
synchronized (lock) {
wakeUp = true;
this.notify();
}
Note that there are simpler and more obviously correct ways to do this using various java.concurrent.* classes.
The case where using synchronized makes sense is where the thing using the lock has state that needs to be protected. In that case the lock has to be held while notifying because there are going to be state changes that go along with the notification, so that requiring notify to be called with the lock makes sense.
Using wait/notify without state that indicates when the thread should wait is not safe, it allows race conditions that can result in hanging threads, or threads can stop waiting without having been notified. It really isn't safe to use wait and notify without keeping state.
If you have code that doesn't otherwise need that state, then synchronized is an overcomplicated/tricky/buggy solution. In the case of the posted code example you could use a CountdownLatch instead, and have something that is simple and safe.

How does JVM notify a thread blocked by `join()`?

The join() method waits for a thread to die. it use wait to do this.
if (millis == 0) {
while (isAlive()) {
wait(0);
}
}
So when the thread exits, how can it notify threads in wait set.
I try to find code in JDK source code, but failed. Can anyone show me the relevant code snippets?
when a thread in wait set, it may check isAlive() so many times for its timeslice, is this a waste?
if isAlive() is false, it just return, that thread is already in wait set. Is the while(isAlive()) necessary?
I try to find code in JDK source code, but failed. Can anyone show me the relevant code snippets?
The pathname for the Thread class in the OpenJDK jdk8u source tree is jdk/src/share/classes/java/lang/Thread.java. The code for join() is below.
The native code where the notifyAll occurs is in Thread::exit in hotspot/src/share/vm/runtime/thread.cpp.
For other releases the paths may be different. (The find command is your friend.)
When a thread in wait set, it may check isAlive() so many times for its timeslice, is this a waste?
That is incorrect.
The "wait set" argument is incorrect. If the current thread can call isAlive() it is not in any wait set. It will only be in the "wait set" for the target Thread when it is in a wait(...) call. It is removed from the "wait set" when the current thread is notified.
To reiterate, a thread t1 is in the "wait set" of another thread t2 when t1 is executing t2.wait(...).
A wait(0) call means "wait until notified without a timeout". (It does NOT mean the same thing assleep(0) or yield()!) Therefore, this is not a busy loop.
The loop will usually go around zero or one time only. (But see the next part of my answer.)
If isAlive() is false, it just return, that thread is already in wait set. Is the while(isAlive()) necessary?
Your "wait set" logic is incorrect (as above).
The loop is necessary. It is possible for any application code that has a reference to the target Thread object to call Object.notify() on that it. That causes the wait(0) to return. But since this "wake up" is spurious, it is necessary to check that the target Thread has actually ended (by calling isAlive()) and maybe waiting again.
This could happen repeatedly ... if application code is doing something silly ... but it shouldn't.
public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) {
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
Most of the implementation of Thread is in native code. That is where the notifyAll that wakes up the joining threads is made.
To answer your questions:
wait() is a native method and uses System code. There is no Java code for that.
wait() is not a means to wait for a Thread but to synchronize on a certain object. Wait() is the wrong method to pause a thread, you need to use sleep().
The counterpart of wait() is notify() or notifyAll(). This will wake up Threads which wait for the calling object. Wait() and notify are part of the Object.class and need a synchronization on the object.
A Thread is alive as long as its run method is executing. If you join a thread the calling thread will automatically halt.
If you want to let a thread wait then use Thread.sleep.
Thread t1 = new Thread(){
public void run(){
try {
sleep(5000);
} catch (InterruptedException e){
e.printStackTrace();
}
System.out.println("I'm done");
}
}
t1.start();
//The calling thread will wait here for 5 sec.
t1.join();

Does Thread#join() let other threads through synchronized blocks?

The Object#wait() method has this funny property that it will allow other threads to enter it's synchronized block while it is blocked in it. Example (assume thread 1 runs first):
Thread 1:
synchronized(someLock)
{
wait();
}
Thread 2:
synchronized(someLock)
{
notify();
}
The fact that thread 2 is able to wake up thread 1 means that thread 2 entered the synchronized block even though some other thread was in a synchronized block on the same object. That's fine with me but I'm wondering if that happens only for Object#wait() or for all methods that would make the thread "wait" (Thread#sleep, Thread#join). In my case I care about Thread#join because if the behavior is the same as Object#wait() it would break my code:
private void waitForClose()
{
try
{
// if one thread is waiting in join the other will wait on the semaphore
synchronized(joinLock)
{
if(outputThread != null && Thread.currentThread() != outputThread)
outputThread.join();
outputThread = null;
if(inputThread != null && Thread.currentThread() != inputThread)
inputThread.join();
inputThread = null;
}
}
catch(InterruptedException ex)
{
logger.error("Interrupted Exception while waiting for thread to join in " + name, ex);
}
}
So is it possible that multiple threads enter this synchronized block because of the join call putting the thread in a waiting state?
First of all the wait and notify mechanism is not really that funny. It is the most rudimentary way of coordinating two or more threads in Java. It is important to understand what is happening here:
Thread 1:
synchronized (someLock) {
System.out.println("Thread 1 going to wait ...");
someLock.wait();
System.out.println("Threads 1 got notified.");
}
Thread 2:
synchronized (someLock) {
System.out.println("Notifying");
someLock.notify();
System.out.println("Exiting block.");
}
The wait() call will relinquish the lock allowing another thread to take hold of it. At this point, thread 1 will not be able to proceed even if it gets notified. This documentation clearly states this:
The awakened thread will not be able to proceed until the current
thread relinquishes the lock on this object.
So it is only after thread 2 exits the synchronized block that thread 1 will proceed with the code after the wait().
Thread.join() is syntactic sugar, a helper method that underneath the hood makes use of the same wait and notify / notifyAll() methods. In fact the javadoc warns against using wait and notify on Thread objects, not to interfere with this mechanism.
This implementation uses a loop of this.wait calls conditioned on
this.isAlive. As a thread terminates the this.notifyAll method is
invoked. It is recommended that applications not use wait, notify, or
notifyAll on Thread instances.
Thread.sleep() is unrelated to wait and notify. It does not need an object's lock, and does not need to be in a synchronized block.
Your code seems to be synchronizing on an object called joinLock while the outputThread.join() will be synchronizing and waiting on the outputThread object. They are unrelated. If anything you might risk a dead lock if outputThread is synchronizing on joinLock. Without the code for the outputThread I can't say.

Need to Stop or Terminate the Thread [duplicate]

This question already has answers here:
How to stop a java thread gracefully?
(6 answers)
Closed 8 years ago.
As i have Written a Simple Java Program to call Thread . below is my code
public class ThreadPoolForParallelExec {
public static void main(String args[]) {
ExecutorService service = Executors.newFixedThreadPool(5);
for (int i = 0; i < 5; i++) {
service.submit(new Task(i));
}
service.shutdown();
}
}
final class Task implements Runnable {
private int taskId;
public Task(int id) {
this.taskId = id;
}
#Override
public void run() {
myclient.intializeAndConnectRemoteMachine(taskId);
Thread.currentThread().stop();
Thread.currentThread().isInterrupted();
}
}
However , I need to terminate the Executor or Thread . I tried Thread.currentThread().stop(); and
Thread.currentThread().stop(); both didnt work :( could you please suggets .
Generally speaking, to kill thread is a bad idea, and in fact, the latest Java specification deprecate that.
Instead, try to finish the thread gracefully within the thread itself. That is the consistent structure.
Just let the method end normally.
Then the Thread will be idle and the ExecutorService will shutdown afterwards.
I think you should call to interrupt() and then wait Threads to finish. Then you could do any actions without having threads running.
you can either use Thread.interrupt() or use volatile flag in run method and set it false when you want to stop thread.
#Override
public void run() {
while (running) {
try {
....
} catch (InterruptedException e) {
running = false;
}
}
}
while running is flag initialized as true.
for more details you can refer this link
The documentation for version 1.5 says:
interrupt
public void interrupt()
Interrupts this thread.
Unless the current thread is interrupting itself, which
is always permitted, 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.
Throws:
SecurityException - if the current thread cannot modify this thread
Never use Thread.stop. It has been deprecated:
From JLS:
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
The good way to do it is to have the run() of the Thread guarded by a boolean variable and set it to true from the outside when you want to stop it.
Make sure you had made the guarding boolean field volatile to make sure the reading thread sees changes from the writing thread.

Can a thread be interrupted in the middle of run()'s synchronized block?

I am writing a simple threading application. Thread is simply a message consumer and process it. However, if the thread somehow got interrupted and the message is not fully processed, I want to put it back to the queue and let other instances get it. So I had to code it like this:
public void run()
{
Map<String, String> data = null;
try
{
while(true)
{
data = q.getData();
System.out.println(this+" Processing data: "+data);
// let others process some data :)
synchronized(this){
sendEmail(data);
data = null;
}
}
}
catch (InterruptedException e)
{
System.out.println(this+" thread is shuting down...");
if(null!=data)
q.add(data);
}
}
Thanks...
EDIT: Thanks for the responses. Everything is very clear now. I understand that even when lines of codes are in a synchronized block, if any of them can throw InterruptedException then it simply means they can be interrupted at that point. The line q.getData() enters this thread to a 'blocked' state (I am using LinkedBlockedQueue inside the q.getData()). At that point, this thread can be interrupted.
A thread will not catch an InterruptedException any time another thread calls interrupt() on it, nor does that method magically stop whatever it's doing. Instead, the method sets a flag that the thread can read using interrupted(). Certain other methods will check for this flag and raise InterruptedException if it's set. For example, Thread.sleep() and many I/O operations which wait for an external resource throw it.
See the Java Thread Interrupts Tutorial for more information.
In addition to David Harkness's answer: you also don't understand meaning of synchronized keyword.
Synchornized is not a kind of "atomic" or "uninterruptable" block.
Synchornized block doesn't provide any guarantees other than that other threads can't enter synchronized block on the same object (this in your case) at the same time (+ some memory consistency guarantees irrelevant in your case).
Therefore usage of synchornized in your case is pointless, since there is no need to protect data from concurrent access of other threads (also, you are synchronizing on this, I don't think other threads would synchronize on the same object).
See also:
Synchronization
Ignoring for the moment that while(true) puts the thread into a CPU loop...
If sendMail does anything that checks for thread interruption it will throw an interrupted exception. So the answer to your question is likely to be a solid yes, the thread can be interrupted within the synchronized block, and you will have to catch the exception and check for that.
That said, InterruptedException is a checked exception, so short of funny buggers being done at a lower level, sendMail should indicate that it can throw InterruptedException.
Yes
Java synchronization means no other thread can access the same lock while a thread has acquired it.
If you don't want any other thread to be able to access a message (or any other object) use synchronized(message) block.

Categories