Suppose I have the following situation:
synchronized void someMethod() {
...
try {
wait();
}catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
...
}
and
synchronized void someOtherMethod() {
...
notify();
}
And the Thread accesses first someMethod, goes into wait and then someOtherMethod notifies it and returns to Runnable state. Does the position of the notify() call in the method matter? I noticed no change in behavior even when I positioned the notify() call at different positions inside the method.
Shouldn't the Thread be notified immediately when the call to notify() is made?
The position of the notify() call within the synchronized block does not matter because by definition, if you are still in the synchronized block, then you still hold the lock.
Shouldn't the Thread be notified immediately when the call to notify() is made?
Yes. Calling notify() puts one of the threads (if any) from the wait queue (waiting for the condition) into the blocked queue (waiting for the lock). This does happen immediately, but the awoken thread needs to get the lock before it can start running. So it is immediately moved out of the wait queue but is still waiting to get the lock.
Btw, I would recommend writing this as this.wait() and this.notify() just to be explicit about which object is being affected.
No, the position of the notify() call within the synchronized block does not matter.
I recommend the style:
class SomeClass {
synchronized void someMethod() throws InterruptedException{
...
while (! someCondition) {
wait();
}
...
}
synchronized void someOtherMethod() {
...
makeConditionValid();
notifyAll();
}
}
Notice the use of a while loop around the wait call. Some JVMs can issue spurious notifies, so there is no guarantee that when a thread is notified, the original condition which caused it to wait is valid. Also, the woken up thread does not get to run until the notifying thread relinquishes the lock; so it is possible that by the time the waiting thread executes the condition is again invalid.
These calls (i.e. Object#wait and Object#notify) need to be made within a synchronized block. Since your method is synchronized, the scope of the synchronized block includes everything within the method. Therefore, positioning is irrelevant to it.
Related
I get confused on the synchronized method. Look at this code below:
public void waitOne() throws InterruptedException
{
synchronized (monitor)
{
while (!signaled)
{
monitor.wait();
}
}
}
public void set()
{
synchronized (monitor)
{
signaled = true;
monitor.notifyAll();
}
}
Now, from what I understand, synchronized means only 1 thread can access the code inside. If waitOne() is called by main thread and set() is called by child thread, then (from what I understand) it will create deadlock.
This is because main thread never exit synchronized (monitor) because of while (!signaled) { monitor.wait(); } and therefore calling set() from child thread will never able to get into synchronized (monitor)?
Am I right? Or did I miss something? The full code is in here: What is java's equivalent of ManualResetEvent?
Thanks
When you call wait on an object that you use to synchronize on, it will release the monitor, allowing​ another thread to obtain it. This code will not deadlock.
Have a look at documentation of wait() method.
Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).
The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.
The key point is the thread releases ownership of monitor and hence you won't get deadlock. Child thread can set the value of signaled and can notify main thread.
I am creating a java application in which I am using three threads to perform three operations on a text file simultaneously.I have a toggle button in my application when I click start i am calling a method call() in which i am creating and starting all these threads and when i click stop i am calling a new method stopcall() in which i write a code to stop all these thread.
public void stopcall() throws Exception {
System.out.println("hello stop call");
synchronized(t) {
t.wait();
}
synchronized(t1) {
t1.wait();
}
synchronized(t2) {
t2.wait();
}
}
But stopcall() method is not working properly whenever i am calling this method my application hanged.I would be grateful if somebody help me and tell me how to use wait and notify in my application
Your application hangs because you are waiting for a locked object.
wait() method hangs the thread until another thread uses notify() on that object.
You have to synchronize the method that accessing the shared object (the file in this case) to enable safe threading. here is an example using a boolean flag to indicate if the resource is currently in use or not.
if in use, the next thread will invoke wait() and will wait for a notification.
meantime when the 'currently using' thread will finish the synchronized block - it will invoke notifyAll() to alert all the waiting threads that the resource is free.
public class TestSync {
private boolean fileInUse = false;
public synchronized void syncWriting() {
// blocks until a the file is free. if not - the thread will 'wait'.
// when notified : will do the while-loop again
while (true) {
if (!fileInUse){
System.out.println("using the free file");
fileInUse = true;
//
// code to write and close the file
//
notifyAll();
return;
}
try {
// wait if file in use. after being notified :
wait();
} catch (InterruptedException e) {e.getMessage();}
}
}
The wait()/notify()/notifyAll() methods are fairly easy to understand.
foo.wait() releases the lock on foo, and then it sleeps until foo is notified, and then in reacquires the lock before it returns.
foo.notifyAll() wakes up all threads that are sleeping in foo.wait() calls. If no threads are sleeping at the moment when it is called, then it does not do anything at all.
foo.notify() is the same as foo.notifyAll() except, it only picks one sleeping thread (if any) and wakes it.
The trick to using wait() and notify() is, suppose that you expect some thread A to wake up thread B with a foo.notify(). How do you guarantee that thread B will already be sleeping in a foo.wait() call before thread A calls foo.notify()?
Remember: If the notify happens first, then it will be "lost". That is, the notify will do nothing, and the wait will never return.
That brings us to the reason why foo.wait() and foo.notify() are only allowed to be called from inside a synchronized(foo) block. You are supposed to use the synchronization, and some shared variable to prevent thread A from wait()ing for a notification that already has happened.
I am new to Java and came across this link: http://tutorials.jenkov.com/java-concurrency/slipped-conditions.html while understanding multithreading in java.
In this tutorial the code below is called out as a good practice to avoid slipped conditions:
public class Lock {
private boolean isLocked = true;
public void lock(){
synchronized(this){
while(isLocked){
try{
this.wait();
} catch(InterruptedException e){
//do nothing, keep waiting
}
}
isLocked = true;
}
}
public synchronized void unlock(){
isLocked = false;
this.notify();
}
}
My doubt is that in case two threads A & B call lock() at the same time and isLocked is true i.e. lock has been taken by some other thread C. Now:
--1 A enters synchronized block first (as only one can obtain lock on monitor-object this and enter a synchronized block)
--2 A calls this.wait() and so releases lock on monitor-object this (wait() call releases the lock on monitor-object http://tutorials.jenkov.com/java-concurrency/thread-signaling.html#wait-notify) but remains inside synchronized block
--3 Now B enters synchronized block (as A has released lock on monitor-object this)
--4 B calls this.wait() and so releases lock on monitor-object this (wait() call releases the lock on monitor-object)
--5 at this moment thread C calls unlock() i.e. sets isLocked to false and calls this.notify()
--6 Now one of A and B come out wait(), then come out of while loop and set isLocked to true
--7 and the cycle continues
So in --3, both A and B are inside a synchronized block at the same time, is it not in violation of the basic multithreading principle that only one thread is allowed inside a synchronized block at a time?
Please clarify my doubt.
A thread can only return from the wait() method if it reacquires the lock on the object it's waiting on. In your scenario, A and B would compete to get the lock, only one of them would get it and the other one would keep waiting until the lock is released again.
From the javadoc (emphasis mine):
The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.
I was reading about thread synchronisation and wait/notify constructs from the tutorial. It states that
When wait is invoked, the thread releases the lock and suspends execution. At some future time, another thread will acquire the same lock and invoke Object.notifyAll, informing all threads waiting on that lock that something important has happened.
Some time after the second thread has released the lock, the first thread reacquires the lock and resumes by returning from the invocation of wait.
AFAIK, if there are multiple threads which can compete for the lock when the first thread is awaken by the notify, any one of them can get to own the lock on that object. My question is, if this first thread itself re-acquires the lock, does it have to start all over from the beginning of the synchronized method (which means, it again executes the code before the while loop checking wait() condition) or does it just pause at the wait() line?
// Does the waiting thread come back here while trying to own the
// lock (competing with others)?
public synchronized notifyJoy() {
// Some code => Does this piece of code gets executed again then in case
// waiting thread restarts its execution from the method after it is notified?
while (!joy) {
try {
// Does the waiting thread stay here while trying to re-acquire
// the lock?
wait();
} catch(InterruptedException e) {}
}
// Some other code
}
A method only gets exited when the thread executing it finishes executing its run method, whether by returning normally or having an exception be thrown that goes uncaught within that run method. The only way for your method to not get executed until one of those things above happens is for the JVM to be killed out from under you (with java.lang.System.exit, killing the java process with kill -9, etc.), or if the method is being run in a daemon thread where the JVM is shutting down. There's nothing weird going on here. The thread that waits gives up the lock and goes dormant, but it doesn't somehow leave off executing the method.
The thread awakened from its call to wait never went anywhere; the whole time that the thread was waiting it was still in the wait method. Before it can leave the wait method it first has to acquire the lock that it gave up in order to start waiting. Then it needs to retest whatever condition it needs to check before it can know whether to keep on waiting.
This is why the guarded blocks tutorial tells you that waits have to be done in a loop:
The invocation of wait does not return until another thread has issued a notification that some special event may have occurred — though not necessarily the event this thread is waiting for:
public synchronized void guardedJoy() {
// This guard only loops once for each special event, which may not
// be the event we're waiting for.
while(!joy) {
try {
wait();
} catch (InterruptedException e) {}
}
System.out.println("Joy and efficiency have been achieved!");
}
Note: Always invoke wait inside a loop that tests for the condition being waited for. Don't assume that the interrupt was for the particular condition you were waiting for, or that the condition is still true.
(The wording used by the tutorial is misleading; the word "interrupt" should be "notification". Also it is unfortunate that the tutorial code shown eats the InterruptedException without setting the interrupt flag, it would be better to let the InterruptedException be thrown from this method and not catch it at all.)
If the thread did "start over" then this loop wouldn't be required; your code would start at the beginning of the method, acquire the lock, and test the condition being waited on.
Thread execution starts directly after the call to wait. It does not restart the block from the beginning. wait() can be roughly implemented similar to
public void wait() {
release_monitor();
wait_monitor();
acquire_monitor();
}
This is no where near how it is actually implemented, it is just a rough idea of what goes on behind the scenes. Each Object has a monitor associated with it that can acquired and released. Only one thread can hold the monitor at a time and a thread can acquire a monitor recursively with no issue. A call to wait on an Object releases the monitor allowing another thread to acquire it. The waiting thread then waits until it is woken up by a call to notify/notifyAll. Upon being woken up the waiting thread waits again to require the Object's monitor and returns to the calling code.
Example:
private Object LOCK = new Object;
private int num = 0;
public int get() {
synchronized( LOCK ) {
System.out.println( "Entering get block." );
LOCK.wait();
return num;
}
}
public void set( int num ) {
synchronized( LOCK ) {
System.out.println( "Entering set block." );
this.num = num;
LOCK.notify();
}
}
"Entering get block." will only be printed once for each call to get()
I'm coming from .NET world, and unfortunately looking Java source with .NET's eyes.
Following code is from Android Apps (though not Android specific at all):
private class Worker implements Runnable {
private final Object mLock = new Object();
private Looper mLooper;
Worker(String name) {
Thread t = new Thread(null, this, name);
t.start();
synchronized (mLock) {
while (mLooper == null) {
try {
mLock.wait();
} catch (InterruptedException ex) {
}
}
}
}
public Looper getLooper() {
return mLooper;
}
public void run() {
synchronized (mLock) {
Looper.prepare();
mLooper = Looper.myLooper();
mLock.notifyAll();
}
Looper.loop();
}
public void quit() {
mLooper.quit();
}
}
I'm not precisely clear with how synchronized works.
First I thought that synchronized is locking mLock object, but then if after t.start() constructor thread enters sync block first, it would block it at mLock.wait(), and implicitly block thread "t" by blocking it from entering synchronized block.
This is obviously wrong, because my phone rings as supposed :)
Next thought is that synchronize synchronizes "code block" (in which case, there two synchronized block are independent => threads can enter two different sync block at same time without restriction), and that fitted perfectly...
... until my colleague told me that mLock.wait() releases lock on mLock and enables other thread to enter critical section on mLock in same time.
I'm not sure if I was clear enough, so will gladly answer any further questions on this.
Check out the javadoc on Object.wait(). It's "magic" in that it drops the monitor that was acquired when entering the synchronized {} block. That allows another thread to acquire the monitor and call Object.notify().
When another thread calls notify() to wake the waiting thread from its wait() call, the waiting thread must re-acquire the monitor and will block until it can -- the monitor is only dropped for the duration of the wait() call. And the notifying thread completes its synchronized block before the newly-awoken waiting thread can proceed. Everything is sequenced predictably.
synchronized uses object monitors. Calling wait() on the object atomically releases the object monitor (for otherwise no other thread could ever take the monitor and issue a notify to the waiter(s)).
Yes. If you read the description of the wait() method, you'll learn that it causes the thread to release the lock and block until another thread invokes notify or notifyAll on the lock. The current thread waits until it can re-acquire the lock, and once it does, it continues execution.
The code shown follows poor practice, however, because it "publishes" (that is, it makes the object accessible to other threads) the Worker instance before it is fully constructed. The use of additional barriers in this method, combined with the private nature of the class, probably make this case safe, but in general, it is not.
Let me explain:
The constructor launches a new thread that will execute the run() method.
This new thread will obtain a new Looper object, store it in the mLooper field and then run the Looper message loop. In between it will notify() the first thread that mLooper has been set.
The first thread will therefore return from the constructor only after mLooper has been set which means that processing of Looper.loop(), by the 2nd thread, is bound to start shortly/has already started.