Concurrent Programming in Java - java

Is the lock retained by the thread when context switch occur.
When we invoke a wait() the locks are given up by thread, what happens when theres a context switch.
Thanks

Yes, locks are retained during a context switch. In fact, that's the whole point of a lock.
When a thread calls wait it relinquishes the lock. When wait returns the lock is re-obtained, so you can guarantee that when control returns to your thread it holds all the locks you expect.

The thread that invoked wait() gets suspended until some other thread invokes notify*() on the object. At that point, when another context switch occurs, the wait() call will return and the waiting thread will immediately try to re-acquire the lock before proceeding further.

Related

Why are wait while-loop conditions safe in a multithreaded context?

I have hard time to really understand, how that works:
while(<some condition>){
wait();
}
OR this example:
while(<some condition>){
condition.await();
}
When thread already passed the <some condition>,
it may really happen, that <some condition> already false when wait() or await() executed.
So wait() or await() may be called with already invalidated condition - that means the intention is broken.
What is wrong with my logic?
From the docs for wait():
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.
(emphasis mine)
In other words, without a synchronized block, your code will throw an IllegalMonitorStateException. With synchronized, on the other hand, your condition will be checked atomically with the wait(); call.
This does not automatically mean you have no problems, because "atomically" here is only with regard to the object you're synchronizing on (in your case this), and only relative to other synchronized access to that object. If your condition depends on different objects, or you access the object without synchronization somewhere else, things might go bad. Thus, don't do that.
The same reasoning goes for the use of Locks and Conditions. See this code sample. Condition variables are derived from lock objects, and synchronized/wait/notify is analogous to lock;unlock/await/signal.
Waking up from Object#wait() or Condition#await() means reacquiring the associated lock. Presumably, <some condition> should only be modified when owning the lock. So if the thread that woke up now owns the lock, no other thread should be able to change the condition to false.

What happens, when two threads try to access a synchronous block?

What happens, when two threads try to access a synchronized block?
Will one of the threads be queued somewhere and access the thread later, or will the thread give up if the trial fails?
Assuming you mean a synchronized block, one thread will manage to acquire the monitor, and the other thread will block until the monitor is released.
See section 14.19 and section 17.1 of the JLS for more details, including:
The synchronized statement (ยง14.19) computes a reference to an object; it then attempts to perform a lock action on that object's monitor and does not proceed further until the lock action has successfully completed. After the lock action has been performed, the body of the synchronized statement is executed. If execution of the body is ever completed, either normally or abruptly, an unlock action is automatically performed on that same monitor.
(Emphasis mine.)
If you need any other semantics - e.g. timeouts - you should use one of the the types in the java.util.concurrent.locks package, so that you can use methods such as tryLock() and tryLock(long time, TimeUnit unit).
Will one of the threads be queued somewhere
Yes, It's queued in JVM and waits until runnig thread frees the lock.
will the thread give up if the trial fails
No, it keeps on trying till JVM is alive. but not trying during while another thread in running the synchronized code.(unless a timeout is specified)
Lets say ThreadA and ThreadB are trying for a synchronized block sb and ThreadB succeeds. Now, ThreadA will wait till ThreadB finishes. in the mean time, suppose ThreadC comes for sb. it sees that the block is being run by some thread and waits in same queue with ThreadA. When ThreadB finishes either ThreadA or ThreadC is given a chance to execute.
So, technically, it's NOT a queue but a similar datastructure.
One of them will wait, forever if necessary (such as the first thread executing an infinite loop), though that would be a rather bad design. There are no timeouts on code execution synchronisation.
From the JLS:
A synchronized statement acquires a mutual-exclusion lock on behalf of the executing thread, executes a block, then releases the lock. While the executing thread owns the lock, no other thread may acquire the lock.
If synchronized block is being executed by another thread then both thread will wait. Otherwise , one thread will be allowed to work upon and another will wait until first thread completes its job.

Method Synchronization

When we declare a method synchronized then how it is known by second thread that the synchronized section of code used by the first thread is completed and how second thread can use that synchronized section of code?
The thread scheduler tells the second thread. When a thread exits a synchronized block stuff happens in this order:
The exiting thread releases its lock.
The lock tells the thread scheduler that it was released.
The thread scheduler changes the state of the threads waiting on that lock to "running".
The running threads race to acquire the lock, one of them wins, the rest go back to waiting.
The scheduler decides which threads to run and what order to run them in and when to context-switch, so it influences which thread gets the lock, but it doesn't directly hand the lock over to the next thread in line. (Who knows, maybe some implementation does, but you can't count on that behavior in general.)
Java uses an internal construct called a monitor to manage synchronization, basically when thread 1 enters a synchronized method, it takes control of the monitor, similarly when it is finished it releases the monitor. Any threads that arrive while the monitor is currently held are blocked until the monitor is released. Then they enter the synchronized method.
here is more information on monitors:
http://en.wikipedia.org/wiki/Monitor_(synchronization)
When it is a non-static method then this is equivalent synchronizing over this:
public synchronized void xyz() { ... }
is equivalent to
public void xyz() {
synchronized(this) {
...
}
}
When it is a static method then it is synchronized over class object instead.
When thread A enters synchronized method, It acquires a LOCK on the Object calling the method, so any other Thread cannot call the synchronized method using that particular object. However any Thread B can call that synchronized method using some other object of the same class.
So once Object is Locked, No thread can call synchronized method using that object until The previous thread release the Lock. and previous thread will release the lock when it has finished executing the synchronized method.
In the mean time if Thread B and Thread C have invoked the same synchrinized method using the same previous object, then they will start waiting for Thread A to release Lock on Object. When Thread A will release Lock on the Object, then Thread B OR Thread C can start executing, There is no guarantee which one will go first. The other one will continue waiting.
Have a look at oracle documentation page to understand concepts clearly.
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.
Every object has an intrinsic lock associated with it. By convention, a thread that needs exclusive and consistent access to an object's fields has to acquire the object's intrinsic lock before accessing them, and then release the intrinsic lock when it's done with them.
A thread is said to own the intrinsic lock between the time it has acquired the lock and released the lock. As long as a thread owns an intrinsic lock, no other thread can acquire the same lock. The other thread will block when it attempts to acquire the lock.
Javaword article by Bill Venners clearnly explains what actually happening under the hoods.
Two opcodes, monitorenter and monitorexit, are used for synchronization blocks
When monitorenter is encountered by the Java virtual machine, it acquires the lock for the object referred to by objectref on the stack. If the thread already owns the lock for that object, a count is incremented.
Each time monitorexit is executed for the thread on the object, the count is decremented. When the count reaches zero, the monitor is released.
Once the monitor is released, one of the waiting threads will acquire the monitor and above process will be repeated again.
Have a look at related SE questions:
What does 'synchronized' mean?
How Synchronization works in Java?

what happens when a thread is interrupted while blocking on a wait()?

Considering the fact that wait() can only be called in a synchronized context which subsequently release the monitor until a notify/nofityAll has been called on the same object by another thread,
Assume Thread A is blocking on a wait() which results in Thread B acquiring the lock. Now if we interrupt Thread A, would control be transferred immediately to Thread A ? in which case, since the try catch block handling the InterrupException is within the synchronized context, and since only one Thread can hold the monitor at a time, what will happen to Thread B ? should it move to a blocked state until Thread A has finished execution ?
Thanks in Advance
Reading the documentation does in fact help:
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Object.html#wait%28long%29
Thus, when the thread is interrupted, it has to re-acquire the Object's monitor to restore the synchronisation state before the exception is thrown. The same holds for returning from the wait(long) call after the specified amount of time has elapsed.
The thread T is then removed from the wait set for this object and
re-enabled for thread scheduling. It then competes in the usual manner
with other threads for the right to synchronize on the object; once it
has gained control of the object, all its synchronization claims on
the object are restored to the status quo ante - that is, to the
situation as of the time that the wait method was invoked. Thread T
then returns from the invocation of the wait method. Thus, on return
from the wait method, the synchronization state of the object and of
thread T is exactly as it was when the wait method was invoked.
If the current thread is interrupted by another thread while it is
waiting, then an InterruptedException is thrown. This exception is not
thrown until the lock status of this object has been restored as
described above.
I believe that A will become runnable but will wait until it can acquire the lock before proceeding with the catch clause. It won't force B into a blocked state. The whole point of a synchronized block is that the thread holding the lock is guaranteed that no other thread can synchronize on the same lock until it gives up its lock; forcing B into a blocked state and letting A reacquire the lock would violate the very essence of synchronization.

java: wait(), notify() and synchronized blocks

I learned that calling an Object's wait() method will release the object monitor, if present.
But I have some questions regarding calling notify() on this object by another thread:
(when) will the waiting thread wake up, if another (a 3rd) thread owns the object monitor in the meanwhile?
will the waiting thread wake up, if a 3rd thread called wait() on this object?
is it possible to determine if a thread is waiting for notifying a particular object (java 1.4/java 5)
What's happening if wait() will be called in the finalize() method?
When you call wait() from a thread, that thread stop executing and it's added to the waitset of the object. When you call notify() from another thread, a random thread from the waitset is waked up, if you call notifyAll() all would be ready to execute.
When you call notify(), the thread is ready to run but it doesnt mean it will be executed inmediately so be careful.
It would wake up a thread from the waitset randomly.
Youd don't know which one will be waked up first, it doesn't follow any order.
Thread.getState()
You would produce deadlock.
notify will wake one thread waiting on the monitor. Unless and until the monitor is unowned, no thread waiting can run; wait() must be called in a synchronized block and so the lock must be held to continue running that block.
No guarantees. Call notifyAll to give all threads a chance to wake.
Dunno. You could have the thread set a variable saying it's waiting before it goes to sleep...
This is probably a bad idea. Can you come up with a situation where this is necessary?
That's why you have the notify() and notifyAll() methods. The former wakes up one thread waiting on the object, the latter wakes up all threads. A waiting thread will not wake up if wait() is called in another thread.
No.
It's only possible to call thread.holdsLock(obj) to see if a thread holds the monitor lock on a particular object.
Don't call wait() in a finalize method.
2: Not necessarily. notify() wakes up one of the waiting threads. It might be the original one or the third one.
3: Using thread.getState() you can find out if a thread is waiting for an object, but I don't know if you can always find out which object this is, exactly.

Categories