ThreadLocal in Java

Sdílet
Vložit
  • čas přidán 28. 12. 2018
  • Use ThreadLocal for thread-safety, memory efficiency and for per-thread context storage.
    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...

Komentáře • 194

  • @SamDLee-vo3tr
    @SamDLee-vo3tr Před 5 lety +29

    thanks for great video!
    One question, at 2:55, since all threads just read the same single global SimpleDateFormat obj, however, no thread tries to change it although it is mutable. How can the data integrity issue turn up? Can I still consider SimpleDateFormat obj as thread safe in your example?
    Of course, we can ensure the data integrity of SimpleDateFormat obj when necessary by using, ThreadLocal, AtomicReference

    • @DefogTech
      @DefogTech  Před 5 lety +43

      True. If SDF only had global state variable, set only once during Constructor, we would not have thread-safety problem. Unfortunately, multiple global variables (eg: calendar) are modified even when format() method is called. Thus if 2 threads use same SDF object, and both call format() at the same time, one thread's format() will call calendar.setTime(date) and then other thread will do the same overriding first thread's date. Thus we need external sync over whole object, or have to use ThreadLocal.
      Source Code (check format method)
      hg.openjdk.java.net/jdk6/jdk6/jdk/file/39e8fe7a0af1/src/share/classes/java/text/SimpleDateFormat.java

    • @windowcrystal4012
      @windowcrystal4012 Před 4 lety

      @@DefogTech Oh I see. But I hope there is a more general case to illustrate this. And Java 8 has introduces DateTimeFormatter to make it immutable, thread-safe

    • @SuganthanMadhav
      @SuganthanMadhav Před 4 lety

      hg.openjdk.java.net/jdk6/jdk6/jdk/file/39e8fe7a0af1/src/share/classes/java/text/SimpleDateFormat.java#l330

    • @rakspatel5159
      @rakspatel5159 Před 4 lety +1

      @@DefogTech How about making the SDF Final? Also if the SDF itself is not changing I did not understand how it impacts the other objects like Calendar? BTW Great work. This Concurrency playlist is awesome. Do you have word of PPT of these tutorials?

    • @MrMikomi
      @MrMikomi Před 3 lety +1

      @@rakspatel5159 final just prevents reassignment of the reference. The problem is that sdf is not immutable - its state changes when it is used to format a date.

  • @vishalsrane
    @vishalsrane Před 5 lety +93

    There is no other tutorial on Java Concurrency which is even half good as yours. Thank you Sir for making these videos. Keep it coming.

    • @Kiran-lr8gi
      @Kiran-lr8gi Před 3 lety

      Yes.but also watch this one czcams.com/video/4ZLkbWWpkyk/video.html

    • @manOfPlanetEarth
      @manOfPlanetEarth Před rokem

      Look for Jakob Jenkov. He is also on the level.

    • @manOfPlanetEarth
      @manOfPlanetEarth Před rokem

      Also, this guy's (defog tech) pronunciation is awful.

    • @theunusual4566
      @theunusual4566 Před rokem

      @@manOfPlanetEarth Jenkov's vids are also good, but Defog's are older than him.. Both are quality providers.

    • @manOfPlanetEarth
      @manOfPlanetEarth Před rokem +1

      @@theunusual4566
      Yeah, they both set the level. Love them both.
      And Geekific as well (discovered him recently, after my above text).

  • @dk5146
    @dk5146 Před 11 měsíci +2

    This is guy is one of the most inspiring geniuses I've ever met

  • @SouravBagchigoogleplus
    @SouravBagchigoogleplus Před 4 lety +6

    After watching your videos, I removed all AsyncTask from my android Java code and introduced Java concurrency. Your videos about multithreading are awesome.

  • @kishorsundar5026
    @kishorsundar5026 Před 11 měsíci +1

    Seeing this after 4 years -it is a gem ! ,I have gone through several tutorials ,I understand and forgot over time ,the way you are explaining wont let you forget even if you want to be :) ,great work and god bless

  • @cpsarathe
    @cpsarathe Před 5 lety +20

    Good Job in a span of 2 day I watched multiple videos and I can tell you your content is enriching for the experienced professionals as well.
    Keep it up.

  • @mostinho7
    @mostinho7 Před 4 lety +4

    2:00
    ThreadLocal creates a separate copy of the object for each thread.
    To avoid multiple threads accessing the same object which isn’t thread safe. Multiple threads can access the same object with locks but that decreases performance. This also avoids each runnable task submitted to a thread pool creating its own object because we can have thousands of runnable
    5:10 implementation
    6:19 can be used to store variable like user, which needs to be passed from one service to the next. Instead of passing it as a param from one thread to the next, we can use threadlocal static variable and set it when a request comes in. So this is setting a context for a thread.
    Spring uses the concept of context in these examples 8:50

  • @saidivinity876
    @saidivinity876 Před 2 lety

    Excellent explantation. In your videos, you are explaining very difficult concepts like Java concurrency to be understandable easily. Thanks for the effort. I will share this to whoever needed. Why there are no videos from you recently. Keep doing your good to work.

  • @shubhamchandra9258
    @shubhamchandra9258 Před 2 lety

    Absolutely brilliant. Crystal clear explanation. Thanks man.

  • @cslxxwilliam
    @cslxxwilliam Před 2 lety

    Its great. Short and sweet. Straight to the point! Thank you

  • @deepgsingh
    @deepgsingh Před 5 lety +1

    Awesome , very beautifully explained.Keep up the great work

  • @ganeshpathak4804
    @ganeshpathak4804 Před 5 lety +1

    Boss you nailed it. Your way of explaining complex things makes it very easy to understand. Thanks and keep posting more videos :)

  • @rohitjain1447
    @rohitjain1447 Před 5 lety

    Covered this one too! Thank you Deepak!!

  • @alissoncpnunes
    @alissoncpnunes Před 3 lety

    Excelent explanation! Very useful examples!

  • @CorDharel
    @CorDharel Před rokem

    Awesome tutorial thank you very much!

  • @harivignesh100
    @harivignesh100 Před 4 lety

    I think your good expertise in concurrency you are doing great job

  • @AbhishekVaid
    @AbhishekVaid Před 2 lety

    Man, you nailed the explanation. Thanks a lot.

  • @diwu7722
    @diwu7722 Před 5 lety +2

    very nice video ! In the second user case, “services” is little misleading, as people would think each service is running on it is own server, “handler” might be better word.

  • @dharmendrabhojwani
    @dharmendrabhojwani Před 5 lety

    Awesome and clear explanation

  • @navneet2935
    @navneet2935 Před 2 lety +1

    You have, hands down, the best content on Java concurrency, of all the resources out there. Really really appreciate the effort you put into you videos, thank you so much for making all these concepts intuitive and easy to ingest.

    • @DefogTech
      @DefogTech  Před 2 lety +1

      Thank you for the kind words!

  • @Kasas90
    @Kasas90 Před 3 lety

    number of likes are misproportioned to the quality content you have provided. great job

  • @prashantnikam4033
    @prashantnikam4033 Před rokem

    Thanks,
    So nicely explained

  • @mayureshmadhavi4085
    @mayureshmadhavi4085 Před rokem

    Thanks...your explanation is really good, straight to the point

  • @MHK958
    @MHK958 Před 10 měsíci

    Best way to explain is what was problem case,what is use of that component or rearm and then explain use of that teram....
    Awesome explanation bro

  • @shashidhar71
    @shashidhar71 Před 3 lety

    For some reason the video thumbnail shows the video is 20mins. Thanks for the great content.
    For viewers: Do write a clean up method (remove()). I forgot it once and it created a huge memory leak!!

  • @alirezaasadi8656
    @alirezaasadi8656 Před 3 měsíci

    your vids are truly informative

  • @AnmolKumar-nz2tm
    @AnmolKumar-nz2tm Před rokem

    Great Video.

  • @laxmisuresh
    @laxmisuresh Před 4 lety

    Clearly explained. Thanks

  • @ChrisAthanas
    @ChrisAthanas Před 2 lety

    The best explanations on the internet

  • @nikhillingam4630
    @nikhillingam4630 Před 9 měsíci

    Wow just excellent !!!

  • @trishithachowdhury7813

    He explained it so well.

  • @lakshanasmelody1652
    @lakshanasmelody1652 Před 4 lety

    Very well explained!!

  • @madhurgwa
    @madhurgwa Před 5 lety +2

    where were you until now? as always awesome stuff.

  • @diptidesai7399
    @diptidesai7399 Před 5 lety

    Superb 👏 thanks ...thanks once again.....

  • @ankurpaliwal9713
    @ankurpaliwal9713 Před 5 lety

    Very well explained

  • @ainuddinb
    @ainuddinb Před 5 lety

    Very useful, clear and concise, would be helpful if you provide some insights on Inheritable Thread local and difference with Thread local.

  • @narendramanikanta7597
    @narendramanikanta7597 Před 5 lety

    Excellent explanation :) Thank you

  • @lachphalleak2459
    @lachphalleak2459 Před 8 měsíci

    Awesome channel 🎉🎉

  • @lovachittumuri
    @lovachittumuri Před 5 lety

    Good video .. please keep on post this kind of video

  • @avijitsharma5050
    @avijitsharma5050 Před 4 lety +7

    Notes for myself:
    Threadlocal.initialize() --> sets the value of threadlocal , it is invoked automatically.
    Threadlocal.get() --> used to fetch value from ThreadLocal
    Threadlocal.set() --> needs to be called manually in order to set some value in ThreadLocal
    Task is different from thread. 3:29 10 threads from Threadpool can do 1000 different tasks

    • @skgyri
      @skgyri Před 4 lety

      How many threads needed for 1000 concurrent users?
      How concurrent users and thread are connected?

  • @gefeizhu3953
    @gefeizhu3953 Před 4 lety

    I'm from China,your video is very awesome!Keep going!

  • @rijin007
    @rijin007 Před rokem

    You are awesome man....thank you so much for doing this.

  • @ERICLAU0304
    @ERICLAU0304 Před 2 lety

    Great video

  • @girirajtomar519
    @girirajtomar519 Před 2 lety

    great explanation

  • @mohammedthahajk7619
    @mohammedthahajk7619 Před 2 lety

    Quality content on Java concurrency

  • @hurrykrishna
    @hurrykrishna Před rokem

    Wonderful 🙏🏿

  • @kunalrai7577
    @kunalrai7577 Před 2 lety

    You are amazing ... Superb explanations like always

  • @RIN-io4wb
    @RIN-io4wb Před 4 lety

    a great video. Best thanks

  • @srikanthgrandhi6668
    @srikanthgrandhi6668 Před 4 lety

    Explanation is really good to understand the concepts. Could you please share/upload any video on L1/L2/L3 cache models

  • @gameplaykingdom9580
    @gameplaykingdom9580 Před 2 měsíci

    Great stuff, thanks! If you could please create such video to explain in the same manner how Transactions works and how to handle Transactions + CompletableFuture it would be great!

  • @johncerpa3782
    @johncerpa3782 Před 3 lety

    Great video, thank you

  • @sbylk99
    @sbylk99 Před 4 lety

    Best explanation ever.

  • @lkoadil1
    @lkoadil1 Před 4 lety

    greattt... holder part was very good example

  • @ZebsP
    @ZebsP Před 5 lety

    Good as always 👌

  • @yanchuntang7750
    @yanchuntang7750 Před 3 lety

    Great job, man.

  • @aneksingh4496
    @aneksingh4496 Před 4 lety

    Excellent videos on Java Concurrency with Real world examples ... Please post some videos on DS and algo as well

  • @jeremythen7239
    @jeremythen7239 Před 5 lety +1

    Just perfect!

  • @Max-si8xc
    @Max-si8xc Před 4 lety

    Thanks! Your video helps me))

  • @kinsleyKJV
    @kinsleyKJV Před 5 lety

    great video

  • @Praksabhijit
    @Praksabhijit Před 4 lety

    Nice video. I think while discussing you can share the latest API s like DateTimeFormatter as a better option so that viewers are aware. Thanks again for making this video.

  • @avinashsakroji1811
    @avinashsakroji1811 Před rokem

    Can you please some videos on RequestContextHolder & SecurityContextHolder ? Your videos are so precise and clear. please keep making good videos.

  • @brijeshpandey218
    @brijeshpandey218 Před 5 lety

    Awesome 😀

  • @Madhavan2020
    @Madhavan2020 Před 5 lety

    Thank you brother for the clear explanation

  • @pankajkumar00001
    @pankajkumar00001 Před 5 lety

    Very good tutorial...but I request you to put part number in Java concurrency playlist.

  • @sureshchaudhari4465
    @sureshchaudhari4465 Před 4 měsíci

    bro may u get blessed with twins and quadraplets and each son or daughter of yours keep creating technical content for this youtube channel

    • @varunchandra153
      @varunchandra153 Před měsícem

      😂😂😂😂😂😂😂😂😂😂😂😂😂😂😂

  • @buzzonwheels5631
    @buzzonwheels5631 Před 2 lety

    Better than the best 💖

  • @engalibadouin5222
    @engalibadouin5222 Před 3 lety

    you awesome man thank you.

  • @balajibalu3240
    @balajibalu3240 Před 5 lety +1

    Thanks !! Can you try make video on Jndi context ....I want to listen this concept by you ....

  • @farhaankazi7134
    @farhaankazi7134 Před rokem

    Hi Defog,
    Very interesting vlog. I like the explanation along with use cases. I have question. You have created static thread local object and then using it in instance method. Meaning static reference is accessed by non-static context. Although It is not issue but could it be not good if ThreadLocal object itself would have been non-static.

  • @yashwanthpotu9756
    @yashwanthpotu9756 Před 3 lety

    great video man :)

  • @lzf804
    @lzf804 Před 4 lety

    Thank you!

  • @anasbouchouha6877
    @anasbouchouha6877 Před rokem

    Thank you

  • @rajanjha673
    @rajanjha673 Před 3 lety

    Great content
    I have one question since we can use Spring Webflux where thread can handle another request instead of waiting for IO in such cases what will haven to thread local in the 2nd Usecase?

  • @andrii5866
    @andrii5866 Před 3 lety

    Thanks for this playlist! Good job!!! I am just wondering if I set Request to ThreadLocal variable, and try to parse the request body a few times. Will it work only for the first time or anytime?

  • @DeepakPandey-ij3bz
    @DeepakPandey-ij3bz Před 4 lety

    Please share the whole code for passing thread local within services. Thanks for amazing Tutorial

  • @rahulgoti3864
    @rahulgoti3864 Před 5 lety

    Thank You

  • @suriyaprakhash
    @suriyaprakhash Před 4 lety

    Nice video.
    @7.28 shouldnt those services be in parallel in the diagram instead of being sequential ?

  • @cseshivaprasad1985
    @cseshivaprasad1985 Před 5 lety +1

    Crisp and precise explanation of concepts as always.
    Below are my observations and queries , please clarify.
    - Use Case #1 : I understand that SDF(SimpleDateFormat) was used as example to explain the concept of ThreadLocal but for practical situations, is FastDateParser class a good alternative to SDF, which is a thread safe version of SDF. Correct me if I m missing anything here.
    - Use Case #2 : In the start of the use case #2, there was a mention of usage of HashMap to store the use id across the threads but when presentation extended instead of
    TheadLocal , only TheadLocal was considered; was it for simplicity of the problem ? If not, I believe TheadLocal would still be required for the scenario mentioned.

    • @DefogTech
      @DefogTech  Před 5 lety

      For point 1, yes it was to illustrate the problem with SDF. Practically we can use other alternative.
      For point 2, it is ThreadLocal, storing user per thread. Internally java may use hashmap to achieve the effect, but from our perspective it's thread specific user.

  • @alixak4304
    @alixak4304 Před 5 lety +1

    great Videos :) Can you please do some Videos about Actor Model in Java ?

  • @premraj.m
    @premraj.m Před 3 lety

    now I understand why we have TheadLocal

  • @mouviem7951
    @mouviem7951 Před 4 lety

    great!

  • @SaurabhSharma-ww3fv
    @SaurabhSharma-ww3fv Před 3 měsíci

    Cleanup is necessary for ThreadLocal, however, if used in SimpleDateFormatter, where is the point once should do the cleanup. It will always be used.

  • @KundanRoy
    @KundanRoy Před 4 lety +2

    your videos are awesome .. just one request whenever you explain something , implement that in program at same time.

    • @DefogTech
      @DefogTech  Před 4 lety +2

      Thanks! I could add live coding, but then videos will become too long and people don't watch long videos

    • @KundanRoy
      @KundanRoy Před 4 lety +4

      @@DefogTech i think you can do it.. i am following your all videos and your explanation is great but problem is that you explain deep concept and without live code it becomes very difficult to implement..

    • @raghavanaliassaravananm1546
      @raghavanaliassaravananm1546 Před 4 lety +3

      @@KundanRoy I agree with Kundan. A great set of video tutorials Deepak. Thank you and appreciate the good knowledge sharing. Keep up the great work! I am sure such intense topics will look great when followed by a coding example. The real good learners would never dislike them ):) Cheers!!!

  • @zdiscover1
    @zdiscover1 Před 2 lety

    Thanks a ton .. can you pls clear one doubt.....Are the first and second example completely two different aspects of ThreadLocal? Because in first example we have seperate threadlocal for each thread but in second we have a global universal threadlocal with the property that it can identify threads.
    If so then can we solve the first problem like the second one? Like creating a global static ThreadLocal array and each its own sdf object in the array?

  • @BhawaniSingh-jc7cw
    @BhawaniSingh-jc7cw Před 3 lety

    thanks :)

  • @piyushkumar2437
    @piyushkumar2437 Před 5 lety +3

    @Defog Tech Coming with one more doubt : As you have mentioned, the SDF will be assigned to the pools of thread(instead of all the tasks) when using ThreadLocal i.e when a thread initially used to execute a task, ThreadLocal initialValue gets called and create SDF obj. Question is if this particular thread(from the pool) is reused for executing another task, will it call the get method of ThreadLocal ? If yes, then it is trying to reuse the already created SDF obj(while executing previous assigned task) which might be in some other state, and required state to run current task can be different, then how would it be threadsafe?

    • @DefogTech
      @DefogTech  Před 5 lety +4

      Yes, it's created only once and 2nd task on same thread will reuse the SDF. Within SDF format method, it sets state and uses it in next statements. So when 2nd task comes it will also set state first (overriding state set by 1st state) and then work on it. Problem only happens when 2 threads simultaneously call format method. Here both tasks of 1 thread call format method one after another

  • @palakjain2505
    @palakjain2505 Před rokem

    can you pls share the ppt that you used while teaching?

  • @riddhishshah2211
    @riddhishshah2211 Před 4 lety +2

    Sincerely appreciate your efforts. Awesome Video. Thanks a lot. I have one doubt though. We said (around 2:10) having *task local* variables (which can be reused) is not good because it creates a lot of extra objects. But wouldn't the extra objects get created only when the task is actually executed by the thread. And also once the task is done, the object will be destroyed ? In that case wouldn't we still be using 10 objects corresponding to the 10 threads at any given point in time ?

    • @DefogTech
      @DefogTech  Před 4 lety +2

      Task objects are created when we call new , so even if they are executed late by thread they still occupy heap. Also, even though object is garbage collected once thread executes the task is still creating and garbage collecting N objects as N tasks (which could be 1000s) instead of fixed number like thread local.

    • @riddhishshah2211
      @riddhishshah2211 Před 4 lety

      @@DefogTech Makes sense. Thank-you for your prompt response. :)

  • @chaitanyapl
    @chaitanyapl Před 5 lety

    Thank you so much :)

    • @DefogTech
      @DefogTech  Před 5 lety

      You're welcome. You had asked for ThreadLocal video right? Thanks much for the suggestion.

  • @Ilaiyarajajj
    @Ilaiyarajajj Před 2 lety

    Can you provide a Thread local sample using String builder instead of Simpledateformat ?

  • @vinaychauhan3349
    @vinaychauhan3349 Před 8 měsíci

    what is different between task and thread @DefogTech

  • @ssssaket
    @ssssaket Před rokem

    I understand that there are many use cases of using Thread local but I could not understand the first use case and how the Thread Local is more memory efficient here.
    As per my understanding ,peak memory usage would 10 date format objects in both case( as Garbage collector would remove the old once, the moment JVM terminates the task of one thread after task completion ).

  • @ganeshjogam7837
    @ganeshjogam7837 Před 3 lety

    What happens in case ThreadLocal is updating reference type will it not effect object shared by other threads

  • @KIRANKUMAR-mh3jz
    @KIRANKUMAR-mh3jz Před 3 lety

    3:50 how it will serve 10 sdf objects for 1000 users..again it is a data consistency problem right. Pls clarify

  • @pratyushprateek2503
    @pratyushprateek2503 Před rokem

    What if the 'SimpleDateFormat' instance is stateless? At 3:02, you are saying that the SimpleDateFormat instance is not a thread safe class, but if it is stateless, then it is thread safe right.

  • @MayankKumar-qt1cu
    @MayankKumar-qt1cu Před 3 lety

    isn't at 2:08 , only 100 dateformat objs would be created since others would be GCed at a given interval of time.

  • @yogeshdixit2823
    @yogeshdixit2823 Před 3 lety

    From ur chanell itself i got 3 concurrency interview questions .
    Finally got rejected and after rejection mail youtube sujjested me ur video

  • @Mig440
    @Mig440 Před 2 lety

    Now how would you change this code if you're using project loom virtual threads? 🤔

  • @piyushkumar2437
    @piyushkumar2437 Před 5 lety +5

    Great video. I have a doubt..in the date format example when we are defining SimpleDateFormat globally i.e private static SimpleDateFormat sf = new SimpleDateFormat(..) at the top and since it is static we are eagerly loading it and we are just trying a get operation on it(ie we just need the sf object we are not modifying this object) why do we even need to make it thread safe??

    • @DefogTech
      @DefogTech  Před 5 lety +4

      SDF internally stores a state. When format mention is called it manipulates that state to calculate/format the date. If multiple threads use same SDF, the common state will cause issues to result of 2 threads.

    • @piyushkumar2437
      @piyushkumar2437 Před 5 lety

      @@DefogTech Ok. Thanks for the clarification :)

    • @prateeksingh3636
      @prateeksingh3636 Před 5 lety

      Navjot Singh SDF is not thread safe class u may find many article on it,
      So its better to have it in lock.

    • @piyushkumar2437
      @piyushkumar2437 Před 5 lety +1

      @Defog Tech Coming with one more doubt : As you have mentioned, the SDF will be assigned to the pools of thread(instead of all the tasks) when using ThreadLocal i.e when a thread initially used to execute a task, ThreadLocal initialValue gets called and create SDF obj. Question is if this particular thread(from the pool) is reused for executing another task, will it call the get method of ThreadLocal ? If yes, then it is trying to reuse the already created SDF obj(while executing previous assigned task) which might be in some other state, and required state to run current task can be different, then how would it be threadsafe?

    • @iliasusalifu6224
      @iliasusalifu6224 Před 4 lety

      @@navjotsingh1081 final does not prevent one from writing to an object; it only prevents variable re-assignment. You can have a final variable pointing to a mutable object that could still be written to by multiple threads. @Defog Tech meant that SDF has instance variables whose values change when methods are called on the SDF instance. Such a class is mutable and thus not thread-safe.

  • @manoranjanm1384
    @manoranjanm1384 Před 2 lety

    If one object per thread can be stored in thread local how Spring stores different context holder in one thread local object?
    Does it uses a map? And sets in the thread local? Can u share a snippet if possible?