This question already has answers here:
Ensure Java synchronized locks are taken in order?
(7 answers)
Closed 9 years ago.
If I use synchronised methods or locks and some threads enter wait queue, do they leave the wait queue in same order as they entered it? In other words, does the first thread to enter wait queue also leave it first?
No, the JVM chooses randomly a Thread to wake from waiting state either one uses notify() or notifyAll() to wake them. In particular with notify() only one Thread will randomly be chosen to enter the excecution state, while with notifyAll() all the waiting Threads together, but there is no guarantee in what order will they be excecuted.
Related
This question already has answers here:
What does 'synchronized' mean?
(17 answers)
Closed 4 years ago.
A Java thread A fails to execute synchronized statement as another thread has got the monitor.
The thread A is queued by the JVM?
And how thread A is activated after, via 1) or 2) ?
As soon as the monitor is released JVM will send up this signal , thread A may be activated
the JVM will detect whether the monitor is available in a period of time, if the monitor is available, thread A may be activated
The Java Language Specification says it in section 17.1 Sysnchronization:
[...] Only one thread at a time may hold a lock on a monitor. Any
other threads attempting to lock that monitor are blocked until they
can obtain a lock on that monitor. [...]
This question already has answers here:
Automatic notify()/notifyAll() on leaving a synchronized block [closed]
(2 answers)
Difference between Synchronized block with wait/notify and without them?
(6 answers)
Closed 4 years ago.
I'm new to thread programming and I have a confusion like below.Let's take the following code block.
synchronized(obj)
{
//do operations
//obj.notify();
//post operations
// last statement
}
Now until the "last statement" executes, the monitor for obj will not be released even after calling notify(). So is it worth calling notify() here?. Because anyway when the synchronized block exits, isn't it equal to calling notify().
No, when you exit synchronized block neither notify() nor notifyAll() is called and all other threads that were waiting on the same lock calling wait() will not be waken up.
Here are some cons regarding automated call to notifyAll()
Automatic notify()/notifyAll() on leaving a synchronized block
When the synchronized block exits, notify if NOT called. It only lets an eventual other thread, that was trying to enter the synchronized block, to proceeed.
notify wakes a single thread that was suspended by a call to the wait method.
The synchronized block will ensure that only one thread can be in that critical section at any one time. Calling notify() on an object will wake up a single thread that is waiting on this object's monitor, i.e. obj.wait().
You don't need to use wait(), notify() or notifyAll() in most cases, including the example above.
I would recommend that you also have a look at the Executor package within Java that handles much of the complexity of you. It's very easy cause all kinds of problems when it comes to threading.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
In Java if a thread, t2, attempts to attain a lock, from synchronized, which is currently in use by another thread, t1, then t2 will switch from runnable to blocked. Correct? What about with ReentrantLocks?
If the thread t1 finishes using the lock, does t2 then automatically switch back to runnable or do you need to use notifyAll()? What about with ReentrantLock usage without a condition. If you aren't using a condition how do you inform the thread t2 that it should switch back to runnable? Is it ever wise, or even possible to use reentrant locks without a condition?
If this question has already been answered (I couldn't find it), I would be grateful if you would link it to me.
It sounds like you're confusing the blocked and waiting states. Blocked means that the thread is trying to acquire the lock and can't so is stuck. Waiting means the thread is dormant; it's hanging out until it receives a notification, or until it otherwise comes back from waiting (timeout, if called with a timeout value, or spurious wakeup).
Once a lock becomes available the OS scheduler has to decide which blocked thread gets it. The thread it picks to get the lock becomes runnable.
So notify pertains to waiting threads, not blocked ones. A thread that has the lock but which has figured out it can't progress (it detects the condition it's waiting for isn't true) can call wait on that lock, releasing the lock and going dormant. You use notify to tell the scheduler to wake up any one thread that is waiting on the lock. Once the thread is woken up it has to reacquire the lock it previously released before it can exit the wait method.
The basic behavior of ReentrantLock is analogous to intrinsic locks, except that you can have multiple conditions with reentrant locks. Keep in mind ReentrantLock has its own separate methods to call (await and signal instead of wait and notify). You would use conditions with ReentrantLock when you want the threads to wait and get notified, with different conditions used so that threads will be waiting only on conditions relevant to them.
If a thread t2 attempts to synchronize on a lock that is currently in use by another thread t1 - for example by attempting to enter a synchronized block when t1 is already in a synchronized block on the same lock - then t2 will block, yes. This is also true for reentrant locks, including the ReentrantLock class; it should be noted that default locks are reentrant in Java (more on this later).
If t1 releases a default lock, such as by exiting the synchronized block, then t2 is unblocked; this is a feature of the language. However, if you are using a ReentrantLock, the thread holding the lock must explicitly call ReentrantLock.unlock() to release the lock, just as it must have called ReentrantLock.lock() to obtain the lock.
Note that "reentrant" refers to whether a single thread can "reenter" synchronized blocks, not to any interaction between threads. Reentrant locks can be locked again by threads that already hold the lock; nonreentrant locks cannot. Note that in Java, if a single thread obtains a reentrant lock more than once, it must release the lock the same number of times before other threads waiting for the lock are unblocked. For default locks, this happens naturally with nested synchronized blocks, possibly at different function call levels.
This question already has answers here:
To multi-thread or not to multi-thread!
(5 answers)
Closed 8 years ago.
I have a general question.
I have been reading a Java book and I came across a program that uses Threads. Book stated that Threads are used for multiprocessing. I want to know that if I write :
Thread t=new Thread(new classname);
t.start;
//after it some GUI code to display the input received from user in run method
and I override run method to get input from user,then, will it wait for input and then perform GUI tasks like opening frame or it will perform both tasks simultaneously.
They'll happen simultaneously. (Unless you block one of the threads using locks or a semaphore.)
If the gui thread relies on the input processing of the other thread, you'll have a race condition. So you'll definitely want to block the gui thread until the other thread is done producing whatever the gui thread needs.
As for why threads are needed, well, it's so tasks can be done simultaneously so programs can do their jobs faster.
This question already has answers here:
Can notify wake up the same thread multiple times?
(4 answers)
Closed 9 years ago.
What happens if you notify a lock, and immediately notify that lock again? Assume there are 2 or more threads waiting on that lock. Is it guaranteed that two threads are woken up? Or is it possible that only one threads is woken up, meaning that the second notification becomes obsolete?
lock.notify();
lock.notify();
Thanks!
Assume there are 2 or more threads waiting on that lock. Is it guaranteed that two threads are woken up?
Yes. Each notify takes a thread from the waiting queue and puts it in the blocked queue -- the awoken thread must first get access to the synchronized lock in question. If there is only 1 thread waiting on the lock then the 2nd notify() would do nothing.
It is important to realize that the thread will not start executing immediately. Since it had to be in a synchronized block on lock to be able to do the wait() it must get access to the lock again before it can run. There may be multiple other threads already in the block queue, waiting to get access to lock.
I suspect the behavior would be similar to calling notifyAll() (in this case it's more like a notifyTwo())
The awakened threads will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened threads enjoy no reliable privilege or disadvantage in being the next thread to lock this object.