Singleton and Double Checked Locking

แชร์
ฝัง
  • เผยแพร่เมื่อ 4 ม.ค. 2025

ความคิดเห็น • 68

  • @dianavlaicu2202
    @dianavlaicu2202 4 ปีที่แล้ว +8

    one remark: regarding your first implementation of the singleton in a double checked manner, you can't use "this" in a static context. synchronize(this) is not permitted, but synchronize(Resource.Class) is working fine.

    • @DefogTech
      @DefogTech  4 ปีที่แล้ว +3

      thats right, i missed that in the video.. static context requires locking on the class

  • @DefogTech
    @DefogTech  5 ปีที่แล้ว +16

    Caution: These 3 patterns are for lazy loading an object. It should be used only when object is very expensive to create and it may or may not be actually called during lifetime of the application.
    In practical scenarios we rarely need lazy load. It can impact performance when first time the method is called. Instead just eagerly create the singleton. In this case application will take some time to start, but the users/threads will not have any impact when calling the method once application is up.

    • @amitmhatre35
      @amitmhatre35 5 ปีที่แล้ว

      Defog Tech bro your videos are very good but just to clarify that enum is not lazily load an object. Above statement is incorrect

    • @trinhduyhung8211
      @trinhduyhung8211 2 ปีที่แล้ว

      Hi Defog Tech. I cannot express how grateful I'm for the videos you made on your channel. They are all simple, elegant, and straight to the point. I would like to see a video where you suggest a list of books that are on your bookshelf or that you're going to read. Thanks!

    • @DefogTech
      @DefogTech  2 ปีที่แล้ว +1

      @@trinhduyhung8211 Thanks a lot for the kind words! I generally read articles, CS papers and such since information is very scattered. But will share whichever books I have found useful.

    • @trinhduyhung8211
      @trinhduyhung8211 2 ปีที่แล้ว

      @@DefogTech Sure thing

    • @AtharvaRao0104
      @AtharvaRao0104 ปีที่แล้ว

      @@rzahir7392 Volatile keyword tells the compiler not to do any reordering because the variable is shared between threads. So along with flushing to memory on every write (happens before) volatile also stops reordering of instructions involving the volatile variable.

  • @PEEYUSHKUMARPATHAK
    @PEEYUSHKUMARPATHAK 5 ปีที่แล้ว +3

    Probably the best video on youtube explaining these concepts!! Please post more such videos :)

  • @zhouchong90
    @zhouchong90 5 ปีที่แล้ว +1

    This is the best concurrency videos! Very clear and useful. Impressed by your depth of knowledge.

  • @gnbhargav
    @gnbhargav 4 ปีที่แล้ว

    Thumba chennage explain madedeera . Good Job. 👏

  • @samirpanchal5883
    @samirpanchal5883 3 ปีที่แล้ว

    This concept is so well explained that you have earned my subscribe. Keep helping the community and posting new videos Thanks

  • @angelvazquez9407
    @angelvazquez9407 3 ปีที่แล้ว

    Excellent video!
    I was looking for an explanation for the 'Double Checked Locking' and they were all very confusing or did not explain some things
    but your video explained it very well.
    also I learned other things like the 'volatile' keyword
    Thank you!

  • @GurmeetSingh-yo4db
    @GurmeetSingh-yo4db 5 ปีที่แล้ว

    nicely explained !!it was being very difficult to understand the double checked locking and use of volatile in singleton but this video make it much more eaiser to understand.thanks!

  • @aman4105
    @aman4105 4 ปีที่แล้ว

    best explanation ever about singleton.

  • @shivanishivu32
    @shivanishivu32 ปีที่แล้ว

    Best explanation 💯

  • @MrMikomi
    @MrMikomi 5 ปีที่แล้ว

    Cool, thanks for this. It reminds me that I have seen developers arguing over whether the singleton design pattern is an anti-pattern. It would be interesting to see you explore this.

  • @kushagraahire1871
    @kushagraahire1871 ปีที่แล้ว

    Very good explanation sir

  • @NileshKumar-yf5cj
    @NileshKumar-yf5cj 4 ปีที่แล้ว

    I am fan of all these videos

  • @bradyadams100
    @bradyadams100 5 ปีที่แล้ว

    Very nicely explained. Great. Keep the good work.

  • @DR02S
    @DR02S 5 ปีที่แล้ว

    Very thorough and well explained brother.

  • @AjitSinghG
    @AjitSinghG 5 ปีที่แล้ว +2

    Great video, thanks! Just one correction, we can not use synchronized (this) in a static method.

    • @DefogTech
      @DefogTech  5 ปีที่แล้ว +2

      right, should've been ClassName.class instead.

    • @govindraokulkarni
      @govindraokulkarni 5 ปีที่แล้ว

      @@DefogTech You might wanna pin this comment or put the correction in the description, you're doing a fantastic work btw :)

  • @JorgetePanete
    @JorgetePanete 3 ปีที่แล้ว

    I didn't know about the constructor operations reordering, very intriguing.
    And the lazy loading of inner classes, where can I find the ins and out of java execution explained in videos?

  • @ravikumar-yq5df
    @ravikumar-yq5df 4 ปีที่แล้ว

    Impressive tutorial

  • @RADHAKRISHANA1
    @RADHAKRISHANA1 5 ปีที่แล้ว

    Good explanation of this concept 👍

  • @shivendratiwari3238
    @shivendratiwari3238 5 ปีที่แล้ว

    Great explanation!!

  • @shkronjax
    @shkronjax 5 ปีที่แล้ว

    Thank You...You clarify concepts well.

  • @bhawanishekhawat2370
    @bhawanishekhawat2370 4 ปีที่แล้ว

    Thanks 👍

  • @warneyfied
    @warneyfied 3 ปีที่แล้ว

    Awesome! Thank you so much!

  • @shilpadolai4228
    @shilpadolai4228 3 หลายเดือนก่อน

    Also enum initializes its instances eagerly right?

  • @Breakdownsmth
    @Breakdownsmth ปีที่แล้ว

    Awesome!!

  • @TheProximator
    @TheProximator 3 ปีที่แล้ว

    Just excellent :) thanks a lot

  • @premraj.m
    @premraj.m 3 ปีที่แล้ว

    at 4:22 where 2nd and 3rd instructions need to be swap... anyway.. thank you very much sir.

  • @shilpadolai4228
    @shilpadolai4228 3 หลายเดือนก่อน

    Can we also say we are making it volatile so that no thread ends up looking at a cached value which might still say that the instance is null and that thread ends up creating another instance?

  • @achyutscience
    @achyutscience 3 ปีที่แล้ว

    Sir, Can you do some more videos on the Java Design Patterns segment. Eagerly waiting for your new videos.

  • @shaileshsharma82
    @shaileshsharma82 3 ปีที่แล้ว

    public Resource getExpensiveResource() shouldn't be a static method?

  • @uniquestreetfood8391
    @uniquestreetfood8391 5 ปีที่แล้ว +1

    Nice video, One correction in static factory method you have used synchronized(this) instead it should be synchronized(Resource.class)

    • @DefogTech
      @DefogTech  5 ปีที่แล้ว

      That's correct. Thanks for pointing out

  • @alfital2
    @alfital2 5 ปีที่แล้ว

    great job. thanks!

  • @kalidindiprashanth7363
    @kalidindiprashanth7363 4 ปีที่แล้ว

    Super.

  • @121brutal
    @121brutal 5 ปีที่แล้ว

    Thanks for this awesome video :)

  • @suryanarayansubudhi9439
    @suryanarayansubudhi9439 5 ปีที่แล้ว

    Thank you.
    Sir if possible please make videos on spring (spring, spring mvc, spring boot, security,cloud )

    • @DefogTech
      @DefogTech  5 ปีที่แล้ว +1

      Yes sir, spring Boot security basics coming next week. Have uploaded web mvc and testing related videos you can check those out

  • @naveensharma9834
    @naveensharma9834 5 ปีที่แล้ว

    Interesting stuff. But as per my understanding there are multiple ways to break this singleton e.g.
    Reflections
    Multiple Class Loaders
    Clone
    Serialize and Deserialiser
    Correct me if I'm wrong.
    Is Enum is the best / unbreakable way to create singleton?

    • @DefogTech
      @DefogTech  5 ปีที่แล้ว

      Thats correct. left those out from the video to keep it short. These days anyways we dont create singletons by hand, its always through some framework like Spring Boot which takes care of the internals.

  • @DeepakPandey-ij3bz
    @DeepakPandey-ij3bz 5 ปีที่แล้ว

    Happen before will work in this scenario so volatile is not required but we are using is it. Please explain

    • @DefogTech
      @DefogTech  5 ปีที่แล้ว

      Because once the singleton is created the next threads will still check if object is present (code before synchronised keyword) so it can just check value of volatile object and avoid locking which can be expensive

    • @AtharvaRao0104
      @AtharvaRao0104 ปีที่แล้ว

      you need to understand what happens when threads use a shared variable which is not synchronized. It will have visibility problems due to optimization techniques used by the compiler to improve performance ( like reordering the instructions or cpu's not flushing the variable to memory choosing to keep it in cpu specific registers) .. By using synchronization techniques (volatile is also one) you can access these shared variables safely without visibility problems.

  • @tvrtkosokolovski
    @tvrtkosokolovski 4 ปีที่แล้ว

    4:30 mark. Can somebody point me to documentation that states this as a fact. The part about order of steps 2 and 3.

  • @AbhishekKumar-fs9nt
    @AbhishekKumar-fs9nt 5 ปีที่แล้ว

    Does the only reason of choosing synchronized block over synchronized method is performance? Otherwise we do not need double checking and all.

    • @DefogTech
      @DefogTech  5 ปีที่แล้ว

      Yes, synchronised method with null check will also be correct but slow

  • @EuropeTransportsArts
    @EuropeTransportsArts 5 ปีที่แล้ว +1

    very great explanation thank you for teaching us,
    i have a doubt that why we need to null check 2 times ? when we check null in first if statement is not fine for inner synchronized block ?

    • @kambalavijay6800
      @kambalavijay6800 3 ปีที่แล้ว

      Hi Devilal, here is the explanation for your question. Let's there are two threads that entered the method and successfully executed condition. Since there is a sync block only one thread(t1) is allowed to execute the body of sync and the other would be under waiting state(t2), imagine if we don't have a condition inside the sync block the other thread that was under waiting state now becomes runnable and creates another brand new object. Thus condition inside the sync block is required.

  • @bhushanraut4446
    @bhushanraut4446 5 ปีที่แล้ว

    Very well explain!! Kudos... Just one doubt - How is the holder pattern thread safe ? Thanks :)

    • @DefogTech
      @DefogTech  5 ปีที่แล้ว

      Thats taken care of by JVM itself. It adds temporary synchronization during init

  • @quantum634
    @quantum634 5 ปีที่แล้ว

    Very insteresting. I didn't really understand the part with the volatile.
    So from my understanding is that when intializing a Resource Object through the constructor the fields can be null ?
    Why would they ever be nulll, except an exception occurs?
    Could you please explain me that ?
    I would have never thought of creating an thread safe singelton through an Enum...!

    • @quantum634
      @quantum634 5 ปีที่แล้ว

      oke so I read into volatile, since I never really had used it before. I think now I do understand it. So basically it ensures that the data from the cpu chache is getting send back to the main memory ?

    • @DefogTech
      @DefogTech  5 ปีที่แล้ว

      Well, you are right about volatile and visibility of updates to threads. Though in case of double checked locking volatile's other guarantee is used which is it will not reorder the empty object to rs and calling the constructor instructions. Thus ensuring when rs is assigned the constructor call has been completed

    • @quantum634
      @quantum634 5 ปีที่แล้ว

      @@DefogTech Would you rather use this pattern or the enum one ? Since using the enum one everything can just be done in one line of code. But there is also an disatvantage. Because what if you want to inherit.
      I don't see why you wouldn't just do this here :
      public class Singleton {
      public static final Singleton INSTANCE = new Singleton();
      /* private constructor, getter, ... */
      }

    • @jeremythen7239
      @jeremythen7239 5 ปีที่แล้ว

      quantum a singleton should not be extended.

    • @DefogTech
      @DefogTech  5 ปีที่แล้ว

      Agreed. That's cleaner. But it's eager loading, not lazy loading. So if Singletons are cheap to create and/or are going to used frequently then this eager pattern is better

  • @creative-freedom
    @creative-freedom 5 ปีที่แล้ว

    Good video. I personally think an enum is the best approach. I'm curious to know if there's a situation where I shouldn't use an enum for singletons?

    • @DefogTech
      @DefogTech  5 ปีที่แล้ว +1

      Generally you don't need lazy loading.. use this pattern only when object is expensive to create and might not need to be created

  • @ajaygupta1
    @ajaygupta1 5 ปีที่แล้ว

    This code wont compile. You cant use "this" inside a static method. Please check

    • @SA-yp6ej
      @SA-yp6ej 5 ปีที่แล้ว

      Please check earlier comments.