Lock's Condition class in Java
HTML-код
- Опубликовано: 18 сен 2024
- Cusing lock.newCondition() to coordinate between threads trying to solve issues like producer consumer problem.
Channel
----------------------------------
Master difficult programming concepts in few minutes. I try to explain difficult concepts like Java concurrency in simple to understand manner using animations and small code snippets. Explore videos on topics like Spring Boot, Cloud Foundry, Java 8 (with more coming soon). I am happy to clarify your doubts. Ask me anything in the comments. I am also happy to take requests for new videos.
New video added every Sunday.
Subscribe or explore the channel - bit.ly/defog_tech
Playlists
----------------------------------
Java Executor Service - bit.ly/exec_srvc
Java Concurrency - bit.ly/java_crncy
Spring Boot 2.0 - bit.ly/spr_boot2
Java 8 - bit.ly/java_8-11
Intellij IDEA Shortcuts - bit.ly/i_idea
Popular Videos
----------------------------------
Executor Service - • Java ExecutorService -...
Introduction to CompletableFuture - • Introduction to Comple...
Understand how ForkJoinPool works - • Understanding how Fork...
Java Memory Model in 10 minutes - • Java Memory Model in 1...
Volatile vs Atomic - • Using volatile vs Atom...
What is Spring Webflux - • What is Spring Webflux...
very good video thank you
beautiful!
When the narrator at 0:17 says, "This condition will depend on your use case," think along the lines of "I want to add an item to a finite queue, but it's full. So, I need to wait here until something else removes one or more items before I can add this item." Or, "I want to take an item from the queue, but the queue is empty. So, I need to wait here until something else puts one or more items into the queue before I can continue." Note that the "something else" (after it has done what you needed it to do) must also signal you to continue.
Absolutely simple & clear explanation. You have a gift for explaining.
Your vídeos are so good and so simple. Thank you for sharing with the world.
You could have showed how threads are called and how condition locks particular thread ,
At 4:43, how can thread0 and thread1 simultaneously wait/block on condition.await()? Isn't the condition.await() surrounded bt a lock.lock()? In that case one of the threads should be waiting to acquire the lock in the first place. Am I missing something here?
This is what Java docs mention - If the lock is held by another thread then the current thread becomes disabled for thread scheduling purposes and lies dormant until the lock has been acquired, at which time the lock hold count is set to one.
Quick Question: 3:19 you are signaling before the unlock statement from the first thread. What would happen to the 2nd thread awaiting on the the condition. If it wakes up before the the unlock method is called by the first thread, the 2nd thread would still not be able to go inside the blocked resource. Would the 2nd go to wait state again or would it automatically enter the blocked resource when unlock is finally executed by the first thread.
excellent video. very neatly described.
during a spurious wake up, a 'if' condition would do the same as while , is there anything specific for using while condition?
I visit this video every year, I try to give like, I find myself already did thank you
I smashed 1000th like . Thanks for uploading for very helpful videos
Great explanation, Thanks for the effort you are put in to make these videos. looking forward to many videos from you
do we ever use wait and notify outside synchronized blocks
or do we ever use condition's await and signal outside lock's lock and unlock?
No for both questions. Both of them should be used within synchronized and lock statements.
Thanks for uploading this and letting us know about the feature of Condition class.
your tutorials are just awesome.. thanks for creating them.. one catch in this video-> Condition doesn't have wait method.. it has await method and its different flavors...
Thank you so much
It's not working for me at all.
Even after signal called on the same condition, the another thread is not resumed, which was awaited earlier.
you are Awesome !!! the concepts related to threads and communications made eazy with simple code examples...thanks for taking this step in giving this super videos.👌
Excellent explanation
pasa codigo
x 2
awesome explanation.
@Defog Tech, great explanation as usual. Is there any way to download the presentations that you use for explaining. It would help quickly to check out in case any pblm with our code.
Because of the lock, they will never run in parallel. When producer finishes smth, consumer takes over, never in parallel. So the computing will be concurrently, similar with sequential. In plus, switching between threads + additional instructions will make this code execute much slower.
Damn Dude, you know so much multi threading....Very Impressive
Excellent video, keep up the good work
Thank you!
Thanks for the session. Great explanation.
Thank you ma'am!
when should i use lock over wait-notify?
I would suggest always. Lock is more flexible than using synchronized. Also condition class has few extra methods which can be handy. Thus use condition wherever possible over wait notify
Very nicely explained!! One little question related to this lock and unlock is happening in try finally block . Can’t we use try , catch finally ?
Yes, absolutely. Unlock has to be in finally because we want to ensure lock is released even if there is an exception. Having catch block is optional.
the sound output of this video is bad in earphones.
I think, the synchronized keyword should be removed from the method and instead the critical section should be enclosed within a synchronized (monitor) block inside the method in the wait/notify example. The synchronized method will lock on the instance of the containing class which is different (probably, don't know if monitor holds a reference to that same instance containing the synchronized method) whereas you are invoking the wait/notify on the monitor object. This can work though, if monitor = this.
7:18 where is the "count" variable coming from?
size of list or data structure where items are added using addData() and removeData() - must be Instance variable.
Great video, enjoyed it! Just one question here, isn't one Conditional variable enough in this case? I don't think you need both added and removed here. Any thought?
i think you can....
the difference is i think in this, the "while" can be an "if", but not in your case
since multiple producers and consumers are there and i wouldnt want a producer's signal to wake up another producer's wait....but in your case the while be evaluated again and await will be hit again...
BUT I CAN BE HORRIBLY WRONG...
I think there is a typo, java.util.concurrent.locks.Condition.await(), not wait(). wait() is part of Object class.
3:58
In order to call either wait() or notify the calling thread must first obtain the lock on that object. At 2:41, synchronized is applied on this object. But the wait/notify methods are called on different object (monitor). Does the code snippet behave as expected?
Yes it does.. the condition is extracted from same lock
@@DefogTech Thanks for quick reply. I was talking about the left side slide which used the synchronized block instead of the lock object and wait/notify methods.
@@krishnak7 Yes if you are using synchronized on a block then synchronized(monitor) should be used.
But @2:41, synchronized method is used and as per my understanding, monitor object should be a static member of that class, so that every instance of that class has common monitor object due to static keyword.
Great explanation!!! Could you talk about java Semaphore?
Sure, will add semaphore video this weekend
@4:45 you say after signalAll is called, depending on the no of cores the JVM can choose to schedule the notified/signalled threads anytime. But isn't only one thread selected for execution at any point of time and others will again go back to waiting state? because they have mutual exclusive lock and even if all threads are notified even if multiples cores exist only one thread can execute the code inside lock() and unlock() at any point of time.
You are right. signalAll will make all threads runnable again. Only one will get chance to acquire lock and actually run. Thanks! Will try to add a card in the video clarifying.
I have a question, why in method 2, the thread-2 has to again acquire a lock? It can simply call signal() method and other threads waiting on this condition can go into runnable state. Unless method 1 and 2 are presumably working on same object, there shouldn't be a need for acquiring lock in method 2. Am I right or confused?
Does conditon.await() remove release the lock? if not ain't a deadlock would occur in case thread a reaches consume then acquired the lock first then another thread b enter produce then it waits for lock to be released
yeah, thats right, once in await, the thread releases the lock. Same is case with normal locks too.
Defog Tech I tried it but method starved and never executed
@Defog Tech, Can we have videos on Reentrant locks please?
Yes sir, coming up next!
2:39, both methods have lock.lock(). So I presume thread1 and thread2 won't execute the method body at the same time because of the lock condition? which means the thread1 will wait forever?
Once a thread calls wait(), it releases the lock and becomes suspended. So when thread1 calls wait, its lock becomes available for thread2, which will call signal/signalAll to wake up thread1. thread1 re-acquires the lock after thread2 completes.
In 1:54 I have a question. Suppose that th1 ins executed first, and it adquires the lock. Then it has to wait conditionMet, but thread 2 can not adquire the lock because th1 has not released it, so it cant signal. What am I missing?
Hi
Sorry if I'm late but
Once await is triggered the thread goes to sleep and releases the lock so the thread that's meant to trigger the notify can acquire it and notify the awaiter
@@oluwanifemiadeyemi4270 Thanks for the response. I checked the java docs and saw it!
@@Norhther
You're welcome!
Why would I put the two methods in different threads and check if the condition is met? Why not just put them in the same method and check conditions in the same thread?
Conditions and concurrency utilities in general are used in presence of multiple threads.. eg: producer consumer. It cannot be implemented in same thread
Do we really need while () { } here or just if () would be sufficient?
Did you find the answer to this? Im new to java and the while loop here seems to defeat the purpose of the wait, the while loop needs another thread to increment a count!
Please provide the coded example to understand better
still don't know what is the difference between wait() and await()
if we can do the same work with wait() then why to use await()
Condition class gives some extra methods which are not present in Object class. Refer docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Condition.html#method_summary. Also Lock Class gives more flexibility than Synchronized. so if you are using Locks and want threads to wait or to be notified - you can go with the Conditions class, it will be much easy.
both producer and consumer use same lock. won't it result in a deadlock?
Nope, locks are released while in wait state
Defog Tech Cool.. Thanks for the clarification.
8:18, so when producer call added.signal(), do it mean producer release the lock of count. Then consumer's await() is triggered, and consumer lock the mutable variant count. Can I understand like this?
When producer calls added.signal, it allows consumer thread to move from waiting state to runnable state. But producer does not release lock when added.signal is called. Consumer will try to re-acquire the lock but it will not be able to, because producer still has the lock. Producer will release lock after lock.unlock, only after this, consumer will acquire the lock and continue its process.
@@DefogTech So when conditionMet.await called the thread is suspended which means the lock that it accuried also will be released?
@@Madhavan2020 ofc, same as wait
typo in condition it is condition.await() method in code slide and not condition.wait()
Agreed. Thanks for pointing it out
Thank YOu!
Another good one from you sir. Thanks for uploading this and letting us know about the feature of Condition class.
You are welcome sir!
Where is the source code?
Sir one doubt,
In a function call, Can we lock on one object, and call "await ()" on another locks conditional object?
Have a look on the api docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Condition.html. It releases the lock when calling await() just like callling object.wait() in a synchronized block. Otherwise you would have gotten a deadlock.