Java ReentrantLock - fairness, tryLock and more

ReentrantLock has become the default way to update a shared state instead of using synchronized blocks. Learn what makes ReentrantLock special
Channel
----------------------------------
Complex concepts explained in short & simple manner. Topics include Java Concurrency, Spring Boot, Microservices, Distributed Systems etc. Feel free to ask any doubts in the comments. Also happy to take requests for new videos.
Subscribe or explore the channel - / defogtech
New video added every weekend.
Popular Videos
----------------------------------
What is an API Gateway - • What is an API Gateway?
Executor Service - • Java ExecutorService -...
Introduction to CompletableFuture - • Introduction to Comple...
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...
Java Concurrency Interview question - • Java Concurrency Inter...

Пікірлер: 121

  • @DefogTech
    @DefogTech5 жыл бұрын

    Apologies for the uneven audio at the beginning... I am trying out a new microphone. Hopefully will be better by next video

  • @fredyoba

    @fredyoba

    5 жыл бұрын

    Don't worry it was good explanation, thanks

  • @nithishreddy9056

    @nithishreddy9056

    5 жыл бұрын

    Please say About lockinterupatability

  • @thomassun3046

    @thomassun3046

    5 жыл бұрын

    Anyway, it is amazing indeed, I also have an suggestion, this video explained the reentrantlock in theory in details, could u plz give me some examples about the real use cases in practice? Like scenarios of online shopping? Thx a lot

  • @kirtigupta8450

    @kirtigupta8450

    4 жыл бұрын

    Must say, awesome explanation

  • @dandantin

    @dandantin

    Жыл бұрын

    This video is excelent. You are the best, keep going make good videos like this one.

  • @learnlearn8230
    @learnlearn82303 жыл бұрын

    Such an amazing explanations in all the videos , you certainly have a crystal clear understanding , and must have put a lot of an effort to understand. Honestly Hats off ....

  • @vilaspaskanti
    @vilaspaskanti4 жыл бұрын

    Quality compilation of material and simple lucid explanation on this channel. Big shout out to Defog tech.

  • @spaarks84
    @spaarks845 жыл бұрын

    Can't stop watching. SO good.

  • @easternadventures9978
    @easternadventures99784 жыл бұрын

    Very well done, thank you for the time you put into this.

  • @abdulrahmanelrawas2029
    @abdulrahmanelrawas2029 Жыл бұрын

    Very clear and concise. Thank you. Subscribed!

  • @madanmohanpachouly6135
    @madanmohanpachouly61353 жыл бұрын

    Thanks a lot, crystal clear explanation.. appreciate your efforts!!!

  • @rahulseetharaman4525
    @rahulseetharaman45254 жыл бұрын

    Excellent explanation. Clear and well articulated.

  • @tedthebed7877
    @tedthebed78774 жыл бұрын

    Lucid explanation. Subscribed.

  • @kbhardwaj1989
    @kbhardwaj19895 жыл бұрын

    Thanks for sharing knowledge.

  • @nazeelak1
    @nazeelak15 жыл бұрын

    Great explanation, Thank you

  • @narayanadhurti1603
    @narayanadhurti1603 Жыл бұрын

    Really defogged my knowledge,Thanks a lot.

  • @mohammedzaid3829
    @mohammedzaid38292 жыл бұрын

    Very clear and precise explanation,,Definitely worth watching

  • @vbar-ukr
    @vbar-ukr3 жыл бұрын

    Fascinating videos!

  • @amitanshupattanayak9065
    @amitanshupattanayak90655 жыл бұрын

    Love your explanations. Keep up the good work..:)

  • @DefogTech

    @DefogTech

    5 жыл бұрын

    Thank you!

  • @suhani091088
    @suhani0910884 жыл бұрын

    Very clear and simple explanation of the concept...

  • @parthec1
    @parthec12 жыл бұрын

    Thank you for creating such wonderful video, kudos

  • @samirallahverdi4948
    @samirallahverdi4948 Жыл бұрын

    Examples are perfect!

  • @monjasonsteng7861
    @monjasonsteng78612 ай бұрын

    Thank you so much. This was great

  • @dvsingh
    @dvsingh2 жыл бұрын

    simply outstanding

  • @harshchaudhary8182
    @harshchaudhary81823 жыл бұрын

    Very good detailed information .

  • @harshadakhandekar4607
    @harshadakhandekar46074 жыл бұрын

    Thanks Defog.

  • @surajtiwari9078
    @surajtiwari90785 жыл бұрын

    Very well explanation.Awesome keep it up .Subscribed User ++.

  • @sukhendurana89
    @sukhendurana895 жыл бұрын

    I absolutely love this channel. Amazing explanation by the creator. Thanks.

  • @Kc-nn8mn
    @Kc-nn8mn3 жыл бұрын

    I like your presentation to make concept easier to understand

  • @guruprasadrao7
    @guruprasadrao72 жыл бұрын

    you're awesome, thanks!

  • @MadMax-sj5fl
    @MadMax-sj5fl3 жыл бұрын

    Extremely good 💯💯💯

  • @SandeepPatel-wt7ye
    @SandeepPatel-wt7ye5 жыл бұрын

    One of the best explanation about the locks. Could you please also includes the lockInterruptibly() method?

  • @BhawaniSingh-jc7cw
    @BhawaniSingh-jc7cw3 жыл бұрын

    great example ..Thanks

  • @VIJAYKAUSHIKTYAGI
    @VIJAYKAUSHIKTYAGI2 жыл бұрын

    love you bro, you explain so good

  • @anirudhgoutam6401
    @anirudhgoutam64013 жыл бұрын

    Amazing Content Bro Keep it Up

  • @prashantranjan4859
    @prashantranjan485911 ай бұрын

    Thanks it's very helpful

  • @jackofnotrades15
    @jackofnotrades153 жыл бұрын

    Good ppl do exist. This guy is a living example.

  • @balakrishnajangita6638
    @balakrishnajangita66385 жыл бұрын

    Awsome boss

  • @SivaKumar-cx7db
    @SivaKumar-cx7db5 жыл бұрын

    Awesome

  • @sureshchaudhari4465
    @sureshchaudhari44656 ай бұрын

    nobody comes close to explain multithreading like you .very nice sir.where do you work

  • @sbylk99
    @sbylk995 жыл бұрын

    The best tutorial to explain reentrant lock and pairness. Thank you, great job!

  • @DefogTech

    @DefogTech

    5 жыл бұрын

    You're welcome! Thank you for the kind words

  • @aqwandrew6330

    @aqwandrew6330

    4 жыл бұрын

    pairness?

  • @shellindebted5328
    @shellindebted53285 жыл бұрын

    Good content and explanation.Thank you.

  • @DefogTech

    @DefogTech

    5 жыл бұрын

    you're very welcome sir!

  • @deepakchauhan25583
    @deepakchauhan255834 жыл бұрын

    amazing is the word

  • @sauravsrivastava7229
    @sauravsrivastava72294 жыл бұрын

    Awesome explanation. Truly love the way you explain and clear the doubts. Would it be possible for you if you can also make videos of explaining the collections internal structures like how does it work? Thanks

  • @DefogTech

    @DefogTech

    4 жыл бұрын

    sure, though I am slightly busy with work so unable to create new videos, please remind me again soon if I miss this

  • @aaron9178

    @aaron9178

    3 жыл бұрын

    @@DefogTech Gentle reminder!!

  • @ganeshradiga
    @ganeshradiga3 жыл бұрын

    Thanks for an amazing video, However I have a question, apart from the recursion you mentioned, are there any practical scenarios where this acquiring the same lock again makes sense

  • @AakashKumar-by1jt
    @AakashKumar-by1jt3 жыл бұрын

    Nice Video..#KeepHelpingUs

  • @tuananhtran7518
    @tuananhtran75189 ай бұрын

    thank you so much

  • @TheNeethz
    @TheNeethz4 жыл бұрын

    like your videos especially on concurrency. Plz create more videos on concurrency

  • @akhilstksa5736
    @akhilstksa57363 жыл бұрын

    thanks bro...

  • @vilaspaskanti
    @vilaspaskanti4 жыл бұрын

    Make a video on ConcurrentHashMap internals, as it uses Reentrant locks on Segments interally.

  • @narendra_ingle
    @narendra_ingle3 жыл бұрын

    Your explanation is too good bro i have just small suggestions that please provide a link for you website where from we can read easily this all

  • @omkarkulkarni9202
    @omkarkulkarni92023 жыл бұрын

    Thanks!

  • @DefogTech

    @DefogTech

    2 жыл бұрын

    Thank you so much for the monetary appreciation. Means a lot to me!

  • @princelowienalasa8776
    @princelowienalasa87765 жыл бұрын

    can you please explain the StampedLock in Java 8 ?

  • @technologiesstepbystep6237
    @technologiesstepbystep62374 жыл бұрын

    @Defog Tech, are these PPTs available somewhere, which is used in video?

  • @rajeshg3570
    @rajeshg35702 жыл бұрын

    Really awesome explanation .. I was read oracle docs on reentrant locks, it has just two lines of documentation.. I've couple of questions here 1. Can we use synchronized block instead of the reentrant lock If there is a recursive function call ? 2. On the trylock() method, how does setting timeout to 0 would achieve the fairness? Please elaborate

  • @vivekdarji6440
    @vivekdarji64404 жыл бұрын

    just want to confirm small doubt. when one thread locked using lock() method then other threads should have state blocked not Waiting. correct?

  • @custardapple5031
    @custardapple50315 жыл бұрын

    Loved the explanation on covered concepts.. very clear ... But some things are not covered e.g what happens when multiple locks are taken and what is the use case here..

  • @cromagnon0101

    @cromagnon0101

    2 жыл бұрын

    Multiple locks could be taken when you are transferring money between accounts. So, for instance there is a worker thread pool which takes in the requests to transfer money from one account to another account. Here upon getting such request we would need to take locks on both accounts, transfer the money and then release the locks to ensure consistent results. Be careful with how the locks are taken and released. Otherwise we might end up in a deadlock.

  • @konfinoyair
    @konfinoyair5 жыл бұрын

    I finally understand what ReentrantLock is

  • @DefogTech

    @DefogTech

    5 жыл бұрын

    Awesome! Good going..

  • @ahamedabdulrahman
    @ahamedabdulrahman4 жыл бұрын

    We shall acieve the same using a boolean variable, right? Like you have explained in "volatile and atomic" video. Can you please tell me any reason why we should not use that boolean way and use reentrant lock way?

  • @sagarshekhar6296
    @sagarshekhar62965 жыл бұрын

    Very Informative.....One question, What is Read/Write Reentrant Locks? Could you please elaborate or create videos if possible?

  • @DefogTech

    @DefogTech

    5 жыл бұрын

    Sure, it's on the list.. publishing this Friday

  • @vinitsunita
    @vinitsunita2 жыл бұрын

    What would be the the real world usecase where you would hold lock multiple times and calling lock method inside a recursive function?

  • @TonyStark-lv4ff
    @TonyStark-lv4ff4 жыл бұрын

    @Defog Tech can you please explain line of code where you use "->" --- what does it mean?

  • @8951348050

    @8951348050

    4 жыл бұрын

    lambda expression introduced in java 8 :)

  • @aashoorajput6500
    @aashoorajput65004 жыл бұрын

    As per your example of recursion ..The current thread count will increase to 2 when it reenter the lock. So lock should also be released Twice....Can you elaborate on this?

  • @06A21A0409
    @06A21A04095 жыл бұрын

    Nice Video, thanks for the informative Video. I have one question. Y we want to acquire the lock more than one time using Reentrant lock.. what is the real usage.??

  • @DefogTech

    @DefogTech

    5 жыл бұрын

    Good question. I couldn't find the best use case for it either. Only possible scenario seems when we need recursion.

  • @sagarshekhar6296

    @sagarshekhar6296

    5 жыл бұрын

    As per my understanding,this can be undestood in following ways: Lets say, there are two synchronized methods , m1 and m2. Lets say m2 is being called inside m1.Lets say there is a common object whose lock is required to access m1 and m2. Now,Lets say Thread t1 accesses the method m1 first and now while processing m1, it enters inside m2 method also.In this case, t1 is not required to again acquire the lock of that common object as it is already holding that(before entering into m1).As the Thread t1 is reentering inside another Synchronized area , this process is said to be Reentrance(entering again). Now, as far as the Locks are concerned,since we are not using synchronized keyword, we will have to apply one lock in m1 and another in m2.Hence, in this case holdCount is 2 now. Hope this helps.

  • @pchandra3277

    @pchandra3277

    5 жыл бұрын

    @@DefogTech Sir , we already have the lock with the working thread, then on recursion senario, why it will be required.?

  • @DefogTech

    @DefogTech

    5 жыл бұрын

    @@pchandra3277 Correct, thread already has the lock, but when recursively thread calls the function again.. and function has lock.lock() as its first line, then thread needs to increase its lock count (it is just called reentrant lock based on synchronized block primitive). So it doesnt really acquire the lock again, it just increases the lock count.

  • @RajKumarSingh-it5sn
    @RajKumarSingh-it5sn5 жыл бұрын

    Excellent tutorial. I have one question, Doest it work for distributed systems?

  • @DefogTech

    @DefogTech

    5 жыл бұрын

    You mean different JVMs? No, it wont.. its for multiple threads within single JVM

  • @RajKumarSingh-it5sn

    @RajKumarSingh-it5sn

    5 жыл бұрын

    @@DefogTech Yes, Thanks

  • @sharanyarai378
    @sharanyarai3785 жыл бұрын

    Great content, but can you share a use-case suitable. as per your example., in real time seat booking, concurrency level is at database/hibernate. Database isolation gives locking mechanism to handle it, so why would i use lock at java level??

  • @DefogTech

    @DefogTech

    5 жыл бұрын

    Agreed, probably not perfect use case. But even here having locking only at DB level will not help. If 2nd user books same ticket, DB update statement will throw exception. Thus concurrency needs to be handled at java level itself

  • @sharanyarai378

    @sharanyarai378

    5 жыл бұрын

    DB will not allow second update statement because that record will be locked by first transcation.

  • @DefogTech

    @DefogTech

    5 жыл бұрын

    Correct, that means at Java level the SQL update query code will have to throw exception or return 0. Then Java will have to handle asking user to book another seat. Again, this is not ideal use-case, completely agree. Will think of a better one and let you know.

  • @sarojsahoo8763
    @sarojsahoo87634 жыл бұрын

    How many locks are available for RenetrantLock

  • @chaitanyapl
    @chaitanyapl5 жыл бұрын

    What is the difference between normal lock object and reentrantlock(false) object. For only fairness purpose should we go to reentrant lock or anyother reason ?

  • @DefogTech

    @DefogTech

    5 жыл бұрын

    Lock is an interface, implementation is Reentrant lock.. this for basic lock functionality we can't use Reentrant lock

  • @manideepkumar959
    @manideepkumar9594 жыл бұрын

    Ur writing l.lock(),but on which object it will try to get the lock??

  • @mohammadfraz5808
    @mohammadfraz58082 жыл бұрын

    Do you have any video on concurrent hashmap?

  • @DefogTech

    @DefogTech

    2 жыл бұрын

    Not yet, I am making one right now, about differences between maps in Java

  • @tarun7597
    @tarun75972 жыл бұрын

    CAn you please exaplain the following statement by Java docs: fairness of locks does not guarantee fairness of thread scheduling. Thus, one of many threads using a fair lock may obtain it multiple times in succession while other active threads are not progressing and not currently holding the lock.

  • @sudarshanv9797
    @sudarshanv97973 жыл бұрын

    I have doubt; tell more about trylock with timeout? I didn't get it properly.I mean what's actually use of it.

  • @vijayakumarvj
    @vijayakumarvj4 жыл бұрын

    Hi bro, I have a query, you described tryLock would not block the thread, it just returns true or false based on the lock availability then how come the concept of fairness comes into picture for trylock. Please explain or I misunderstood the logic?

  • @786PrvN
    @786PrvN5 жыл бұрын

    I didn't understand the point you said in the video that "when calling method recursively that's we it is reentrant lock" But the same thing will happen with synchronized lock also. On the same object, they are also reentrant(stackoverflow.com/questions/13197756/synchronized-method-calls-itself-recursively-is-this-broken) , so is this is fare to say based upon this point that they are reentrant.

  • @DefogTech

    @DefogTech

    5 жыл бұрын

    Yes, absolutely. Synchronized keyword based locks are also Reentrant in nature

  • @AruneshSrivastava
    @AruneshSrivastava4 жыл бұрын

    Does only reentrant lock works with recursive functions... what will happen if i try to use some other implementation of lock in a recursive method ?

  • @DefogTech

    @DefogTech

    4 жыл бұрын

    yes recursive functions with reentrant lock is good! If lock is not reentrant, the recursive function will become deadlocked

  • @hyperborean72
    @hyperborean722 жыл бұрын

    I do not see where and how you attach a lock to a shared resource: fine, you do lock.lock() but on what object?

  • @jozi_mob
    @jozi_mob5 жыл бұрын

    I just wanted to ask , if the Reentrant Lock works in the same way as synchronized block , then why does the Thread trying to access the lock unsuccessfully , go into a "waiting" as it suggests in the video. Shouldn't it be in a blocked state just like synchronized does? Thanks

  • @DefogTech

    @DefogTech

    5 жыл бұрын

    I use the term waiting state even for threads entering synchronized blocks. Basically threads are parked aside waiting for something to happen

  • @jozi_mob

    @jozi_mob

    5 жыл бұрын

    Thanks for the reply. Just wanted to ask , would the specific state for a thread unsuccessfully accessing the lock be the Blocked state. This is the state that the Java API mentions in it Thread Life Diagram.

  • @akankshamittalsinghal
    @akankshamittalsinghal5 жыл бұрын

    Is there any PDF tutorial present for the same

  • @DefogTech

    @DefogTech

    5 жыл бұрын

    Not yet. I am planning to include it in a course I am making

  • @hyperborean72
    @hyperborean72 Жыл бұрын

    The idea of the reentrant lock when the lock can be called multiple times on the already locked object remains absolutely value and unclear. What's the point to call .lock() multiple times? what exactly happens when you call .lock() again and again?

  • @venkataramanan2381
    @venkataramanan23814 жыл бұрын

    12:31 even without setting fair as true can we achive fairness?

  • @DefogTech

    @DefogTech

    4 жыл бұрын

    In that case the fairness is not guaranteed by JVM. It may or may not be fair based on workload, other threads in the system and scheduler configuration

  • @venkataramanan2381

    @venkataramanan2381

    4 жыл бұрын

    @@DefogTech I meant in work around example in which you created an unfair lock. Thanks for you reply.

  • @AbhishekVaid
    @AbhishekVaid8 ай бұрын

    8:25 a major source of confusion. lock.lock() will cause other threads to get blocked, but when it's called by same thread again (one holding the lock) it doesn't get blocked. This needs explanation.

  • @binoydeka810
    @binoydeka8102 жыл бұрын

    hawahawwai :D

  • @DeepakPandey-ij3bz
    @DeepakPandey-ij3bz5 жыл бұрын

    Lock should be maintained per seat not to the whole seat chart. Please suggest

  • @DefogTech

    @DefogTech

    5 жыл бұрын

    Well, thats good point, though what happens when a user tries to book A1 to A10 seats and another user selected A8 to A12... you have to atomically allow or deny seat booking in such overlaps

  • @DeepakPandey-ij3bz

    @DeepakPandey-ij3bz

    5 жыл бұрын

    We should have instances of all the seats in concurrent hash map. Thread pick the seat or an instance of the seat from map and we place lock on that seat instance. If two thread try to lock the same seat which is locked by thread then it should not allow it's booking give some message.

  • @DeepakPandey-ij3bz

    @DeepakPandey-ij3bz

    5 жыл бұрын

    Overlapping case will be interesting to solve with this approach

  • @DefogTech

    @DefogTech

    5 жыл бұрын

    Makes sense.. worth a try implementing

  • @DefogTech

    @DefogTech

    5 жыл бұрын

    Btw, when we are booking say A1 to A10 tickets... even if locks are in concurrent hashmap, we will have to book each ticket in a for loop (get lock, book, unlock)... when we first check A1 to A10, all seats and locks might be available, but when we actually run the for loop, A1 to A7 will be booked but A8 will give error.. then A1 to A7 will need to be rolled back to unbooked It seems tricky to implement. Single lock per whole chart might be simpler.

  • @AndreySaroul
    @AndreySaroul2 жыл бұрын

    I guess, that other threads go into BLOCKED state, not WAIT state on slide 1:10

  • @kirankumar-oe5fz
    @kirankumar-oe5fz3 жыл бұрын

    Tutorials are very much informative but unable to digest fastly getting confused