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.
Related
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.
The following code did not block when the spawned thread tried to obtain the lock on itself.
Does the spawned thread inherits locks from the spawning thread?
Here's the code:
public class A {
public void methodA() {
public class SpawnedThread extends Thread {
public void run() {
synchronized(this) {
...
}
};
SpawnedThread spawnedThread= new SpawnedThread ();
synchronized(spawnedThread) {
spawnedThread.start();
spawnedThread.join();
};
...
}
}
Threads don't inherit locks from other threads, something else is going on here.
In your example the thread that is running methodA has to take the lock on the spawnedThread before it can enter the synchronized block.
Then when the spawnedThread runs it must acquire the lock on itself in order to enter the synchronized block in the run method.
So the methodA thread has the lock and spawnedThread is trying to get the same lock. But it won't deadlock because Thread.join performs waits where it gives up the lock, see the api documentation for Thread.join:
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.
The version of Thread.join without a timeout value takes the lock on the thread it's joining, gives it up, and goes dormant. It doesn't wake up until one of the following happens:
1) the thread being joined finishes (sending a notification that wakes the waiting thread)
2) the joining thread is interrupted (meaning something calls interrupt on it, which doesn't happen in this example)
3) the joining thread wakes up on its own (a "spurious wakeup", which is rare, a result of a race condition)
I'm not clear on how you would change the locks to get a deadlock here as you described in your comment, if you want that answered please add that version of the code to your question.
Does the spawned thread inherits locks from the spawning thread?
No, nor do you hold any lock in the spawning thread for the spawned thread to inherit.
You can attempt to do this with a Lock but it will throw an IllegalMonitorStateException if you try.
"synchronized(spawnedThread) { spawnedThread.start(); };" after instantiating spawnedThread.
As soon as you exit this block, the spwaned thread can obtain the lock. Move the join() inside the synchronized block if you want to see a deadlock.
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.
I'm very confusing about these two descriptions:
"The wait method blocks the calling thread and gives up the monitor lock"
"The notify method unblocks one waiting thread but does not give up the monitor lock"
Here is my questions:
I know each object in Java has a lock, but what is the "monitor lock" means? is it the same as the oject's lock?
Why notify method needs to give up the monitor lock?
If I try to make a object waiting with the following code:
class simpleTask extends Thread
{
int waitingTime;
public simpleTask(int waitingTime)
{
this.waitingTime = waitingTime;
}
public void run()
{
synchronized(this) // this is a reference of current object
{
try {
this.wait(waitingTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Like the first description above, is that means the the current object is blocked by synchronized keyword, and then wait method releases the lock?
I know each object in Java has a lock, but what is the "monitor lock" means? is it the same as the object's lock?
Yes, they are the same thing. They are also occasionally called the object's "mutex" and the object's "primitive lock". (But when someone talks about Lock, they are talking about this Java interface ... which is a different locking mechanism.)
Why notify method needs to give up the monitor lock?
The notify method doesn't give up the lock. It is your code's responsibility to give up the lock (i.e. leave the synchronized block or return from the synchronized method) after the notify call returns.
Why is that necessary? Because any other thread that is currently waiting on that lock (in a wait(...) call) has to reacquire that lock before the wait call can complete.
Why did they design notify / wait like this? So that they can be used to implement condition variables.
Like the first description above, is that means the the current object is blocked by synchronized keyword, and then wait method releases the lock?
That is correct. When a thread calls someObject.wait() its lock on someObject is released ... and then reacquired (by the same thread) before the wait() call returns. Of course, in the meantime the lock someObject may have been acquired and released multiple times by other threads. The point is that when wait returns, the thread that called wait will have the lock.
Yes, the monitor lock is the same as the object's lock. If you do synchronized (object), that's the lock.
In your example, the current object will give up the lock while waiting, the wait() call gives up the lock. In another thread, notify() is called to wake the object up, and when the wait() call returns it will hold the lock again.
A monitor is a type of synchronization construct.
The reason that waiting gives up the lock is so that other threads can acquire the lock, such as other threads that might want to wait. Also: It's usual for the thread that's awakening other threads to lock before releasing any threads, to prevent a race condition.
For more about this, you should study condition variables (i.e. condvars).
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.