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...

Комментарии • 93

  • @naruhitoabiku9451
    @naruhitoabiku9451 7 месяцев назад

    very good video thank you

  • @OmkarKulkarni-d9b
    @OmkarKulkarni-d9b Месяц назад

    beautiful!

  • @scottloewke5199
    @scottloewke5199 6 месяцев назад

    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.

  • @rajivr1944
    @rajivr1944 5 месяцев назад

    Absolutely simple & clear explanation. You have a gift for explaining.

  • @lucasguaru
    @lucasguaru 11 месяцев назад

    Your vídeos are so good and so simple. Thank you for sharing with the world.

  • @Bhushan1234able
    @Bhushan1234able 3 года назад

    You could have showed how threads are called and how condition locks particular thread ,

  • @AnimeshPaul23
    @AnimeshPaul23 5 месяцев назад

    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.

  • @jayak3768
    @jayak3768 6 месяцев назад

    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.

  • @tarankaranth8782
    @tarankaranth8782 2 года назад

    excellent video. very neatly described.

  • @anmolmonga8564
    @anmolmonga8564 7 месяцев назад

    during a spurious wake up, a 'if' condition would do the same as while , is there anything specific for using while condition?

  • @yotubecreators47
    @yotubecreators47 2 года назад

    I visit this video every year, I try to give like, I find myself already did thank you

  • @vishvapradhan8476
    @vishvapradhan8476 Год назад

    I smashed 1000th like . Thanks for uploading for very helpful videos

  • @kranthikumar2004
    @kranthikumar2004 4 года назад +2

    Great explanation, Thanks for the effort you are put in to make these videos. looking forward to many videos from you

  • @shameekagarwal4872
    @shameekagarwal4872 Год назад

    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?

    • @DefogTech
      @DefogTech  Год назад +1

      No for both questions. Both of them should be used within synchronized and lock statements.

  • @itharsh09
    @itharsh09 2 года назад

    Thanks for uploading this and letting us know about the feature of Condition class.

  • @ankitagrawal3468
    @ankitagrawal3468 5 лет назад +2

    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...

  • @omsonschicago5872
    @omsonschicago5872 4 года назад

    Thank you so much

  • @veeraniranjanchiruvella658
    @veeraniranjanchiruvella658 2 года назад

    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.

  • @uma_mataji
    @uma_mataji 2 года назад

    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.👌

  • @puterich
    @puterich 5 лет назад

    Excellent explanation

  • @javierlezamaalonso3337
    @javierlezamaalonso3337 3 года назад +1

    pasa codigo

  • @jaykishankapat41284
    @jaykishankapat41284 5 лет назад

    awesome explanation.

  • @mohitiyer8607
    @mohitiyer8607 4 года назад +7

    @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.

  • @Matzul98
    @Matzul98 3 года назад

    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.

  • @rahulchandrabhan
    @rahulchandrabhan 3 года назад

    Damn Dude, you know so much multi threading....Very Impressive

  • @mustaphag
    @mustaphag 5 лет назад +1

    Excellent video, keep up the good work

  • @sharanyarai378
    @sharanyarai378 6 лет назад

    Thanks for the session. Great explanation.

  • @confuzior
    @confuzior 6 лет назад +9

    when should i use lock over wait-notify?

    • @DefogTech
      @DefogTech  6 лет назад +15

      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

  • @abhishekkrishna9757
    @abhishekkrishna9757 6 лет назад +1

    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 ?

    • @DefogTech
      @DefogTech  6 лет назад +3

      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.

  • @alphazero0
    @alphazero0 9 месяцев назад

    the sound output of this video is bad in earphones.

  • @AyushmanAdhikary
    @AyushmanAdhikary Год назад +1

    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.

  • @Yan-rv8mi
    @Yan-rv8mi 3 года назад +1

    7:18 where is the "count" variable coming from?

    • @devendrawangikar2890
      @devendrawangikar2890 3 года назад

      size of list or data structure where items are added using addData() and removeData() - must be Instance variable.

  • @wengeda9533
    @wengeda9533 4 года назад +1

    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?

    • @shameekagarwal4872
      @shameekagarwal4872 Год назад

      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...

  • @arnold5090
    @arnold5090 3 года назад +1

    I think there is a typo, java.util.concurrent.locks.Condition.await(), not wait(). wait() is part of Object class.

  • @krishnak7
    @krishnak7 5 лет назад +1

    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?

    • @DefogTech
      @DefogTech  5 лет назад +1

      Yes it does.. the condition is extracted from same lock

    • @krishnak7
      @krishnak7 5 лет назад

      @@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.

    • @jaisamtani303
      @jaisamtani303 2 года назад

      @@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.

  • @passeam
    @passeam 6 лет назад

    Great explanation!!! Could you talk about java Semaphore?

    • @DefogTech
      @DefogTech  6 лет назад

      Sure, will add semaphore video this weekend

  • @prasannakumar-pg6lr
    @prasannakumar-pg6lr 6 лет назад +1

    @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.

    • @DefogTech
      @DefogTech  6 лет назад

      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.

  • @mpvkarthick
    @mpvkarthick 4 года назад

    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?

  • @abdelrahman2348
    @abdelrahman2348 4 года назад

    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

    • @DefogTech
      @DefogTech  4 года назад +1

      yeah, thats right, once in await, the thread releases the lock. Same is case with normal locks too.

    • @abdelrahman2348
      @abdelrahman2348 4 года назад

      Defog Tech I tried it but method starved and never executed

  • @sagarshekhar6296
    @sagarshekhar6296 6 лет назад

    @Defog Tech, Can we have videos on Reentrant locks please?

    • @DefogTech
      @DefogTech  6 лет назад +2

      Yes sir, coming up next!

  • @hualiang2182
    @hualiang2182 4 года назад

    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?

    • @pengliu9987
      @pengliu9987 4 года назад

      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.

  • @Norhther
    @Norhther 3 года назад

    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?

    • @oluwanifemiadeyemi4270
      @oluwanifemiadeyemi4270 3 года назад

      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

    • @Norhther
      @Norhther 3 года назад

      @@oluwanifemiadeyemi4270 Thanks for the response. I checked the java docs and saw it!

    • @oluwanifemiadeyemi4270
      @oluwanifemiadeyemi4270 3 года назад

      @@Norhther
      You're welcome!

  • @divyangshah99
    @divyangshah99 5 лет назад

    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?

    • @DefogTech
      @DefogTech  5 лет назад +1

      Conditions and concurrency utilities in general are used in presence of multiple threads.. eg: producer consumer. It cannot be implemented in same thread

  • @computerforhack9526
    @computerforhack9526 5 лет назад

    Do we really need while () { } here or just if () would be sufficient?

    • @lutherschultz4725
      @lutherschultz4725 3 месяца назад

      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!

  • @sanjoyganguly9721
    @sanjoyganguly9721 5 лет назад

    Please provide the coded example to understand better

  • @adarshverma3372
    @adarshverma3372 3 года назад

    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()

    • @devendrawangikar2890
      @devendrawangikar2890 3 года назад

      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.

  • @creative-freedom
    @creative-freedom 5 лет назад

    both producer and consumer use same lock. won't it result in a deadlock?

    • @DefogTech
      @DefogTech  5 лет назад +1

      Nope, locks are released while in wait state

    • @creative-freedom
      @creative-freedom 5 лет назад

      Defog Tech Cool.. Thanks for the clarification.

  • @sbylk99
    @sbylk99 5 лет назад

    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?

    • @DefogTech
      @DefogTech  5 лет назад +1

      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.

    • @Madhavan2020
      @Madhavan2020 5 лет назад

      @@DefogTech So when conditionMet.await called the thread is suspended which means the lock that it accuried also will be released?

    • @ntapasar89
      @ntapasar89 4 года назад

      @@Madhavan2020 ofc, same as wait

  • @SujeetGupta-hx6sl
    @SujeetGupta-hx6sl 5 лет назад

    typo in condition it is condition.await() method in code slide and not condition.wait()

    • @DefogTech
      @DefogTech  5 лет назад

      Agreed. Thanks for pointing it out

  • @2010lakshitha
    @2010lakshitha 3 года назад

    Thank YOu!

  • @shellindebted5328
    @shellindebted5328 6 лет назад

    Another good one from you sir. Thanks for uploading this and letting us know about the feature of Condition class.

  • @asdfasdfasdfasdf219
    @asdfasdfasdfasdf219 5 лет назад

    Where is the source code?

  • @JKThoughts9
    @JKThoughts9 4 года назад

    Sir one doubt,
    In a function call, Can we lock on one object, and call "await ()" on another locks conditional object?

    • @jipadan
      @jipadan 3 года назад

      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.