Java Synchronized - The synchronized keyword in Java and Java synchronized blocks and methods

Ғылым және технология

Java synchronized blocks are either methods or blocks within methods which are synchronized. Synchronized blocks help solve concurrency problems like race conditions, data visibility, instruction reordering etc.
A Java synchronized block is synchronized on a specific "monitor object". Only one thread can enter any synchronized block synchronized on the same monitor object. Multiple synchronized blocks can be synchronized on a shared monitor object.
Chapters
0:00 Java synchronized - introduction
0:10 Java synchronized keyword
0:15 Synchronized instance methods
0:55 Synchronized blocks inside instance methods
1:36 Synchronized block monitor objects
6:15 Example of threads calling synchronized instance methods on a shared object
8:59 Synchronized static methods
11:21 Using both synchronized static and instance methods
13:44 Using different monitor objects for synchronized blocks within same class
15:25 Sharing monitor objects across different class instances (objects)
16:23 Monitor objects cannot be null
16:50 Example of sharing monitor objects across objects
20:58 Don't use String constant objects as monitor objects
22:13 Java synchronized blocks inside Java Lambda Expressions
25:34 Java synchronized block reentrance rules
27:41 Java synchronized block data change visibility guarantee
33:14 Java synchronized block visibility example
36:00 Java synchronized block happens before guarantee
40:48 Java syncronized block limitations
42:42 Java synchronized block performance overhead
43:56 Java syncrhronized blocks in clustered setups
Java Memory Model - JSR 133
www.cs.umd.edu/~pugh/java/mem...
Java volatile tutorial - textual / video:
tutorials.jenkov.com/java-conc...
• Java Volatile
Java Concurrency & Multithreading Playlist
• Java Concurrency and M...
Java Memory Model
tutorials.jenkov.com/java-conc...
• The Java Memory Model ...
Java Happens Before Guarantee
tutorials.jenkov.com/java-conc...
• Java Happens Before Gu...
Java Lambda Expressions
tutorials.jenkov.com/java/lamb...
• Java Lambda Expressions

Пікірлер: 194

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

    Not a single video on KZread matches this level of clarity and extensiveness about multithreading. Hats off to you.👌

  • @JakobJenkov

    @JakobJenkov

    Жыл бұрын

    Thank you 😊

  • @halavich9672

    @halavich9672

    7 ай бұрын

    Totally legit!

  • @fuadgafarov
    @fuadgafarov3 жыл бұрын

    I am never seen tutorials with such clear explanation. Thank you Jakob.

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    Thanks! I am glad you found my tutorials helpful :-)

  • @shubhamagarwal1434
    @shubhamagarwal14342 ай бұрын

    God of Concurency..i have bene flowing you since my 2014 when you used to write blog post only...by going through your post i attend interview like a LION when they ask mutithreading qns.......Thanks a Lot form 10+ yrs exp guy from BLR,India.

  • @JakobJenkov

    @JakobJenkov

    2 ай бұрын

    Thanks :-)

  • @zhenlinjin3142
    @zhenlinjin31423 жыл бұрын

    Thank you, Jakob! You're awesome. I was having difficulty understanding the those mutlithreading concepts while preparing for big-n interviews. Your videos and blogs help tremdously!

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    I am happy to hear my tutorials have helped you! 😊

  • @RaghuVN
    @RaghuVN3 жыл бұрын

    A few years back, one of my friends suggested your tutorial for angularjs. It was easy to understand tutorial, compared to a lot of tutorials I went through. I searched for you and found this playlist of java multithreading, which is equally good. Great and very useful content. Thanks for sharing it. You deserve a lot more views and subscribers.

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    You are welcome! :-)

  • @calumjb
    @calumjb3 жыл бұрын

    These are the best tutorials I have ever seen on KZread, ever, for anything. I rarely comment but I have to thank you. Keep up the good work and I'm positive you'll go far.

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    Wow - thank you very much for your kind words!! :-)

  • @stylishsannigrahi
    @stylishsannigrahi3 жыл бұрын

    The way you explain and takes deep dive, makes you to stand out from others ..amazing stuff.. much gratitude

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    You are welcome! :-) ... it is actually possible to dive even deeper into all these topics - about what happens inside the Java VM etc. - but since the VMs change over time, going so deep might not be up-to-date in a few years.

  • @simongupta8724
    @simongupta87242 жыл бұрын

    Wow, thanks so much for this video. I just started the topic multi-threading and when I got the first infos about it, so many questions were left open. Your tutorial made many things a lot clearer and I certainly will go on watching more of your videos for details on other aspects like the Happens Before Guarantee. It's so great, that there are videos/video collections like this on youtube which cover the topics with some deepness.

  • @JakobJenkov

    @JakobJenkov

    2 жыл бұрын

    Thank you very much for your kind words! I am happy that my videos have helped you ! :-)

  • @LOKeshrangineni
    @LOKeshrangineni3 жыл бұрын

    Thanks Jakob. I used to be a follower of your site a long time ago. Luckily I have found your video on youtube when I wanted to revisit my skills on threads. Very nice explanation with different examples. Thanks a lot for your efforts in providing quality content.

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    You are welcome! I've got more videos on Java concurrency coming :-)

  • @LOKeshrangineni

    @LOKeshrangineni

    3 жыл бұрын

    @@JakobJenkov I am waiting here for your future videos. Meanwhile going through your blog in preparing for an interview.

  • @viranchpatel5071
    @viranchpatel50712 ай бұрын

    This Multithreading playlist is something invaluable! Hats off to you Jakob :)

  • @JakobJenkov

    @JakobJenkov

    2 ай бұрын

    Thank you very much! I am happy it's useful to you ! :-)

  • @marcusrigonati7784
    @marcusrigonati77843 жыл бұрын

    I thought "Let me see some explanation so I can understand a little bit more about Sync" and then this video explains perfectly everything I need to know, thank you man!

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    Great to hear ! :-) ... this video became longer than I had originally planned, but then I thought - why not just go deep into the details now that I am at it?

  • @shilankalhor2072
    @shilankalhor20723 жыл бұрын

    I think after all these years working with java, this is the first time I have understood the synchronization. Many thanks. I wish you also had videos about nio and io. It’s just easier when you explain them.

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    Thank you 😊

  • @waresnite
    @waresnite3 жыл бұрын

    One of the Best java concurrency tutorials that i've found. Keep It up! pls!

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    Thanks! I will try! :-)

  • @OKelvinClark
    @OKelvinClark3 жыл бұрын

    I have to watch these videos at least twice because the content is too complex for my head. Thank you very much for making this matter clearer and easier to understand. This motivates me not to give up on this subject and keep learning.

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    I have books that I have read up to 5 times before I finally understood and remembered it all... just gotta keep at it. If I don't understand one book, or only part of it, I will try another one, and another one etc. Or another article, tutorial or video. Piece by piece I understand more and more of the topic, and one day I understand most of it.

  • @Jaraqqeh
    @Jaraqqeh2 жыл бұрын

    I like your tutorials because you cut to the chase and describe everything clearly and with minimum bs.

  • @JakobJenkov

    @JakobJenkov

    2 жыл бұрын

    That's what I try to do - so I am glad that is also your perception!

  • @ChamaChama205
    @ChamaChama2052 жыл бұрын

    Thank you for being thorough and for doing a great job of explaining everything, this was very informative and helpful!

  • @JakobJenkov

    @JakobJenkov

    2 жыл бұрын

    You are very welcome :-)

  • @druzzyaka
    @druzzyaka2 жыл бұрын

    the best explanation of java multithreading i've ever seen

  • @JakobJenkov

    @JakobJenkov

    2 жыл бұрын

    Thank you :-)

  • @bharatprakashparakh9601
    @bharatprakashparakh96015 ай бұрын

    Best explanation on this planet ! Thank you for creating such a wonderful content

  • @JakobJenkov

    @JakobJenkov

    4 ай бұрын

    You are welcome! :-)

  • @abdurrehman7234
    @abdurrehman72343 жыл бұрын

    If i need to learn something in Java, First thing that comes to mind is your blogs and YT channel, Amazing content

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    Thank you very much ! I am happy to hear that !! :-)

  • @shirshendudebroy2097
    @shirshendudebroy20974 жыл бұрын

    Awesome Tutorials on Concurrency... I was going through the Udemy Java course but now I am only watching your videos... Love from India...

  • @JakobJenkov

    @JakobJenkov

    4 жыл бұрын

    Haha - cool - thanks 😁

  • @magzhanabdibayev3818
    @magzhanabdibayev38183 жыл бұрын

    Thank you, Jakob. Really well explained

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    You are welcome! Glad it was helpful!

  • @hotbarango
    @hotbarango3 жыл бұрын

    Best video on the internet on the topic! 👍

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    Wow, thanks! :-)

  • @e2bvideos
    @e2bvideos2 жыл бұрын

    Great videos Jenkov, very helpful. One more thing that could be done is that, you can upload the diagrams and code to a git repo. That would be really helpful

  • @crazy-boy6143
    @crazy-boy61432 жыл бұрын

    AWESOME. A pretty clear explanation. Could fix an annoying bug in my code thanks to you. I appreciate it

  • @JakobJenkov

    @JakobJenkov

    2 жыл бұрын

    Great ! :-)

  • @hussamkd6327
    @hussamkd63272 жыл бұрын

    Perfect explanation. Thank you!

  • @JakobJenkov

    @JakobJenkov

    2 жыл бұрын

    You are welcome :-)

  • @isurucumaranathunga
    @isurucumaranathunga3 жыл бұрын

    Such a outstanding explanation. Thank you so much

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    You are welcome, Isuru :-)

  • @omnipoten8
    @omnipoten84 жыл бұрын

    Excellent explanation. Would like this to be the video that should be used in classrooms to explain Java synchronization to students . Thanks for the video !

  • @JakobJenkov

    @JakobJenkov

    4 жыл бұрын

    Thank you very much :-) ... well, aren't many students anyways supplementing their classroom material with KZread and online tutorials?

  • @omnipoten8

    @omnipoten8

    4 жыл бұрын

    @@JakobJenkov I am sure they are :-) . I just wanted to make this video official to be presented in classrooms ;)

  • @kundanKumar-cc7qt
    @kundanKumar-cc7qt Жыл бұрын

    Thanks, Jakob. The content is very useful.

  • @JakobJenkov

    @JakobJenkov

    Жыл бұрын

    Great! :-)

  • @VLADICA94KG
    @VLADICA94KG3 жыл бұрын

    Thank you so much for such a concise and clear presentation! Please keep uploading such a great content!

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    You are welcome! Glad it helped you! ... I will continue making more videos when I have time :-)

  • @mdziaularfeen8436

    @mdziaularfeen8436

    3 жыл бұрын

    @@JakobJenkov Please do, specially contents which are usually misunderstood or not explained by many will help a lot. Grateful for your work. 😊

  • @gaminggot8472
    @gaminggot84723 жыл бұрын

    Great movie, thank you Jakob!

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    You are welcome - and thank you too! :-)

  • @jeffenriquez9929
    @jeffenriquez99292 жыл бұрын

    Thank you for making this video!

  • @JakobJenkov

    @JakobJenkov

    2 жыл бұрын

    You are welcome :-)

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

    Amazing, thank you so much!

  • @JakobJenkov

    @JakobJenkov

    Жыл бұрын

    You are welcome 😊

  • @Jay-nc1wr
    @Jay-nc1wr9 ай бұрын

    You have an amazing skill to teach and describe complex topics in a easy to understand manner, thank you. I agree, you should make a course and put your material on there.

  • @JakobJenkov

    @JakobJenkov

    8 ай бұрын

    Thank you very much !! I might make a course one day ! :-)

  • @dominikpiegdon248
    @dominikpiegdon2483 жыл бұрын

    Really, really good tutorial, thanks Jakob for it! ;)

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    You are welcome! :-)

  • @taoma9293
    @taoma92936 ай бұрын

    Great lesson! 😊

  • @JakobJenkov

    @JakobJenkov

    6 ай бұрын

    Thank you !! 😊

  • @devtoro5601
    @devtoro56012 жыл бұрын

    i'm so Lucky to know this lecture. thanks!

  • @JakobJenkov

    @JakobJenkov

    2 жыл бұрын

    You are welcome! Glad you liked it! :-)

  • @athisii_ekhe6167
    @athisii_ekhe61672 жыл бұрын

    Very helpful. Thank you.

  • @JakobJenkov

    @JakobJenkov

    2 жыл бұрын

    You are welcome! :-)

  • @sajjadvalaei2535
    @sajjadvalaei25352 жыл бұрын

    I appreciate your content thank you.

  • @JakobJenkov

    @JakobJenkov

    2 жыл бұрын

    You are welcome! :-)

  • @islombekmamatqulov7821
    @islombekmamatqulov78212 жыл бұрын

    Thank you very much Jakob

  • @JakobJenkov

    @JakobJenkov

    2 жыл бұрын

    You are very welcome! :-)

  • @sagnik4u007
    @sagnik4u0073 жыл бұрын

    Awesome explanation

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    Thank you! :-)

  • @meetanupam
    @meetanupam2 жыл бұрын

    Excellent!

  • @JakobJenkov

    @JakobJenkov

    2 жыл бұрын

    Thank you! :-)

  • @minepolz320
    @minepolz3204 жыл бұрын

    Thanks for the video very good explanation

  • @JakobJenkov

    @JakobJenkov

    4 жыл бұрын

    You are welcome :-)

  • @rishabhdhiman2865
    @rishabhdhiman286511 ай бұрын

    You are like Andrew Ng of multithreading, breaking down things to their fundamentals

  • @JakobJenkov

    @JakobJenkov

    11 ай бұрын

    Thank you 😊 I think Andrew Ng knows more about AI than I knoe about concurrency, though 😊

  • @SoeaOu
    @SoeaOu3 жыл бұрын

    great stuff, explained well

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    Thanks! :-)

  • @sangsokea
    @sangsokea2 жыл бұрын

    thanks so much sir, that help me save the time a lot

  • @JakobJenkov

    @JakobJenkov

    2 жыл бұрын

    That's great! :-)

  • @thushalyaweerasuriya4641
    @thushalyaweerasuriya46413 жыл бұрын

    it is really good..thank you ..love from srilanka

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    You are most welcome :-)

  • @-boiadeiro-
    @-boiadeiro-3 жыл бұрын

    very nice video & examples

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    Thank you! 😃

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

    Great tutorials

  • @JakobJenkov

    @JakobJenkov

    Жыл бұрын

    Thank you very much :-)

  • @iurysza
    @iurysza3 жыл бұрын

    Excellent material! This what people actually need when learning this concepts. While I'm very happy this content is free, I hope you open some kind of funding for your videos so you can keep doing them. Please keep doing what you're doing =)

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    Thank you very much !!! I Once opened a patreon account, but I did not get any backers, so I closed it again 😁 ... so now I just make standard videos with a bit of ads in... not a big deal, but it pays a coffee from time to time 😁

  • @abhisheksengupta4159

    @abhisheksengupta4159

    3 жыл бұрын

    @@JakobJenkov This is really a noble work, Thanks for sharing your knowledge :D

  • @EpicKillstreak

    @EpicKillstreak

    3 жыл бұрын

    @@JakobJenkov Agreed that this is a great content, explained very well, thank you. One thing you could always do is to put a link to PayPal in the description, so those who want can actually thank you in that way. : 3

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

    Hello Jakob! The tutorials are very good, have helped me very much! A note for 21:40 . I think Java saves strings to String Constant Pool. So if a String is already in the pool, java returns that and it does not create a new string object.

  • @JakobJenkov

    @JakobJenkov

    Жыл бұрын

    Constant strings may be stored in the String constant pool. But as far as I know, a new String("value") would not. But to be sure - it's better to just stay away from using String objects as monitor objects.

  • @yonatanshkolsky4396
    @yonatanshkolsky43962 жыл бұрын

    Wow. you explained this better then my professor!!!

  • @JakobJenkov

    @JakobJenkov

    2 жыл бұрын

    :-D ... I am happy it helped you. To be fair to professors, with videos you can go back and rewatch until you understand it. That's not possible with a live professor lecture - so the experiences will probably be different :-) ... but in a live lecture you can ask questions - which you cannot do to a pre-recorded video...

  • @suttonc1338
    @suttonc13382 жыл бұрын

    Hello, Jakob. I found your website by accident and was amazed by the quality of your content. Excellent job! If you make any Udemy course, please let me know. I would love to buy your class. Keep up the good work.

  • @JakobJenkov

    @JakobJenkov

    2 жыл бұрын

    Hi Sutton, thank you very much for your kind feedback! :-) I don't have any Udemy courses available - but I am thinking about writing a book soon. It will be about some advanced Java topics though... maybe not that interesting for everyone :-)

  • @garimadhanania1853
    @garimadhanania18533 ай бұрын

    Awesome!

  • @JakobJenkov

    @JakobJenkov

    3 ай бұрын

    Thank you ! :-)

  • @user-ri4tw2dw9q
    @user-ri4tw2dw9q3 жыл бұрын

    Finding this treasure through your blog JenKov! From today, i Fucking Love Danish! haha

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    Thanks :-D ... happy to help people all around the world with the stuff that was hard for me to learn!

  • @Premkumar-eq1zv
    @Premkumar-eq1zv Жыл бұрын

    You are legend 🙂

  • @JakobJenkov

    @JakobJenkov

    Жыл бұрын

    Thank you 😄

  • @khomo12
    @khomo122 жыл бұрын

    Great!

  • @JakobJenkov

    @JakobJenkov

    2 жыл бұрын

    Thanks 😊

  • @mrrishiraj88
    @mrrishiraj8810 ай бұрын

    thank you.

  • @JakobJenkov

    @JakobJenkov

    9 ай бұрын

    You are welcome! :-)

  • @OmprakashYadavIIT
    @OmprakashYadavIIT3 жыл бұрын

    simple awesome..

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    Great to hear you liked it! :-)

  • @vipul1246
    @vipul12463 жыл бұрын

    Can't believe this stuff is free. I don't think any paid course about multithreading can match this level.

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    Thanks :-D ... well, the more we all know, the better software we can write, and the better it is for everyone ;-)

  • @vipul1246

    @vipul1246

    3 жыл бұрын

    @@JakobJenkov keep making these free content for all. So , those who can't afford can still also gain knowledge.

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

    thx

  • @JakobJenkov

    @JakobJenkov

    Жыл бұрын

    Welcome :-)

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

    14:32 This is just a reminder for me when I come next time to watch

  • @smitalpatel
    @smitalpatel3 жыл бұрын

    In the example around 7:34 , viewers can try removing the synchronized keyword from method signature. You will see the diff in output. I got below Set Object : 0 Get Object : null Get Object : 0 This means without synchronization, 2 threads could enter set & get method at same time. And even though the set method was called first it couldn't complete assigning value 0 to obj variable, & so Thread 2 calling Get method printed null. And just after printing null, the Get method printed 0 as the set method must have completed assigning the value 0 to obj. This can be called Race Condition. This will not happen in case the method is synchronized, the Get method will always print what set method has printed last, because only one thread can enter either method & once entered it will surely complete its task first. FYI: I printed the values inside the set & get method in the first lines of respective methods. So value assignment is after the print.

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    Good experimentation work ! It's fun to see how practice corresponds to the theory, right? 😊

  • @smitalpatel

    @smitalpatel

    3 жыл бұрын

    @@JakobJenkov exactly Jakob. BTW thanks for this video. Forgot to thank you as i was too focused on example. I am good in Java. But never was i this clear on the topic. This video helped me a lot. Also i wrote same code to understand it more clearly, which also allowed me to experiment. Thanks a lot again.

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

    Incredible explanations… How did you learn all of this? Or have you been told by somebody else

  • @JakobJenkov

    @JakobJenkov

    Жыл бұрын

    I had to read a lot of books and articles, and watch videos and presentations. It's hard to find good information about Java Concurrency.

  • @cypherllc7297
    @cypherllc72976 ай бұрын

    Hi Jakob, Does using a synchronized keyword on a function mutex lock all the objects that are either directly in the scope of that function or called inside that function? Cause the Autowired beans I have used are getting locked and hence blocking parallel runs.

  • @JakobJenkov

    @JakobJenkov

    6 ай бұрын

    No - it only "locks" the object which the synchronized block is synchronized on - which is either "this" or an explicit object passed as argument to the synchronized block construct. Objects that are referenced from inside a synchronized block can be referenced from outside that synchronized block too - without being blocked. Of course it is up to you to determine if you want that or not (often you don't want that - because why would you reference the object from inside a synchronized block if you do not want access to it to be guarded ?)

  • @asankasiriwardena3383
    @asankasiriwardena33832 жыл бұрын

    Thanks Jakob! I have a question regarding the final section (synchronized blocks in multiple JVMs) though. As I know same object cannot be shared across multiple JVMs. Therefore is it fair to talk about thread blocking across multiple JVMs on same synchronized block? Or do you intend an edge scenario like a common JNDI store across multiple JVMs to share an instance?

  • @JakobJenkov

    @JakobJenkov

    2 жыл бұрын

    You cannot block threads across multiple JVMs with a synchronized block. You will need to implement a different mechanism to block threads across multiple JVMs.

  • @asankasiriwardena3383

    @asankasiriwardena3383

    2 жыл бұрын

    @@JakobJenkov Assume We have somehow managed to share an object across JVM, only then we can apply any other different mechanism to block threads across JVMs?

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

    35:42 @JakobJenkov It took me a few minutes to understand how could both threads reach 2 million after adding the synchronized keyword to both getCound() and incCount() methods, as it did not make sense first, as I thought that the thread finishing its execution first would reach at most (2M - 1). But I think I get it now: the code in the runnable implementation/lambda is not synchronized, only the methods that they are calling. So it could happen that the two getCount() calls in the Sysout statements will be executed just after both for-loops are finished. Maybe it would worth a little explanation, as a minute before you seem to be hinting to something similar to my initial thought -- although that first statement is not exactly clear. Or am I missing something? :) Love your videos btw, cheers!

  • @JakobJenkov

    @JakobJenkov

    Жыл бұрын

    I agree, normally one thread reaches 2M-1 or lower when finishing, and the other thread reaches 2M. But - in rare situations they might both increment their final time almost simultaneously, and then both will obtain 2M when getting the count.

  • @lilianetop8307
    @lilianetop83073 жыл бұрын

    @ 35:38 Why is the count of Thread1 != 2M? The methods are synchronised so I expected that both Threads would end op with 2M.

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    One of the threads will finish its 1 million iterations before the other. That is inevitable. The thread that finishes first will not see a total count of 2 million. The highest possible count it can see is 1.999.999 - since the other thread is not yet finished with its 1.000.000 iterations.

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

    how do you do the desing of this concurrency software? can do this with the UML? how do you do the abstraction process?and is it include on any of your videos? on the object orientation paradigm, and functional paradigm can be a plus

  • @JakobJenkov

    @JakobJenkov

    Жыл бұрын

    Pen and paper :-) ... I don't use any special software or techniques.

  • @KlanBr1

    @KlanBr1

    Жыл бұрын

    @@JakobJenkov and what about the relation between entities how do you identify? i mean in poo you have 3 kind of relation between entities, it's the same when you have concurrency?

  • @DeepakLalchandaniProfile
    @DeepakLalchandaniProfile4 жыл бұрын

    Hi Jakob, Can you upload the examples to your website as a zip file for download ?? Please reply ( I cannot copy and try it on ide ) ☹☹

  • @JakobJenkov

    @JakobJenkov

    4 жыл бұрын

    I am getting more requests for the code behind videos. Always first check out the link to the textual tutorial in the description below the video for code samples. Maybe in the future I might add a GitHub repo for code examples.

  • @DeepakLalchandaniProfile

    @DeepakLalchandaniProfile

    3 жыл бұрын

    Hi Jakob, 1. I just checked for the textual tutorial link for Java synchronized. It is not updated in the description of this video 2. Looking forward for your github code of Concurrency

  • @9229rohit
    @9229rohit2 жыл бұрын

    @Jakob , which books do you refer to ?

  • @JakobJenkov

    @JakobJenkov

    2 жыл бұрын

    Where?

  • @9229rohit

    @9229rohit

    2 жыл бұрын

    @@JakobJenkov I really appreciate your deep knowledge and this helped me brush up my 10 years old concepts . That time I used to study from Cathy Sierra for Java 6 . would love to know which books do you refer now and if you can suggest some 😊

  • @mohamedkhaled6370
    @mohamedkhaled63702 жыл бұрын

    Hello Jakob, I really appreciate your content But I think there is a mistake here 24:44 You've said that we cannot use "this" as a monitor inside a lambda as Lambdas don't belong to any object, but the error is actually because of that you cannot access "this" from the static main. I have passed "this" as monitor to lambda inside an instance method and it worked, Hope you clarify.

  • @JakobJenkov

    @JakobJenkov

    2 жыл бұрын

    I would not be able to comment on that without seeing the code. Passing "this" from outside of a lambda into a lambda - is not the same as referencing "this" directly inside the lambda. Nor is refereencing "this" via the class where the lambda is created - as this references the "this" belonging to the object outside the lambda - not the lambda itself.

  • @mohamedkhaled6370

    @mohamedkhaled6370

    2 жыл бұрын

    @@JakobJenkov Hi again :) Here is the Code public class LambdasAndMonitors { static Object object; public static void consumeObject(Consumer consumer){ // not synchronized consumer.accept(object); } } // main LambdasAndMonitors.consumeObject((obj) -> { synchronized (this){ // there is a Compile error here regarding "this" System.out.println(obj.toString()); } }); The error says: "this" cannot be referenced from a static Context // which is the main method and the suggestion is: Make 'main' not static

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

    Thanks for the great lessons but I have one question: Let's say in Main RAM the counter is 0. Then in Thread #1 we increment counter right before synchronized block therefore in our local cache or CPU register this value is 1. And when we go into synchronized block it leads us to read value again from Main RAM where the value is still 0. Does it mean that we lost incrementation eventually? The code like this: public void someMethod() { counter++; // 1 synchronized(this) { counter++; // 1 or 2? Will we lost incrementation here since synchronized block guarantee that we update value from Main RAM where the value is 0? } }

  • @JakobJenkov

    @JakobJenkov

    Жыл бұрын

    I am not actually sure what would happen in that situation. Obviously you *should* increment the counter inside synchronized block - not outside - but if you did what you show in the code example there, I am not sure what the final result would end up being.

  • @ivanocj
    @ivanocj4 жыл бұрын

    I don't know why, but in your videos KZread keep using 360p as default to me. I need to manually change to 1080p. It is not my connection (240Mbps) because I watch many other ones with very good resolution. That happens only with videos in your channel.

  • @JakobJenkov

    @JakobJenkov

    4 жыл бұрын

    Strange... the videos are uploaded in 4K !

  • @LOKeshrangineni

    @LOKeshrangineni

    3 жыл бұрын

    @ivan - mine is playing at 720 p without any manual intervention. so definitely something with your internet connection.

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

    About one of the problems you mentioned, when the write method to the monitor object has to be written by a single thread at a time, but multiple threads should be able to read, Can't we solve that using a single synchronized method for writes , but for read we keep it non synchronized?

  • @JakobJenkov

    @JakobJenkov

    Жыл бұрын

    No. If you have the read method non-synchronized you lose the thread visibility guarantee of the synchronized block. In other words, you have no guarantee about when a reading thread will refresh it's currently cached value (of a variable) from main memory (which in practice is somewhere in the cache memory).

  • @sahilkalamkar5332

    @sahilkalamkar5332

    Жыл бұрын

    @@JakobJenkov Thanks for the confirmation. Also when using synchronized blocks for counters, it's not guaranteed that the values are flushed and refreshed from RAM right? So should we use volatile keyword as well?

  • @KuldeepYadav-jw7jn
    @KuldeepYadav-jw7jn3 жыл бұрын

    What will happen if we provide new String("some") reference as a monitor object? Will it work?

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    In theory, that should work. However, the convention is to either synchronized on just an Object instance, or synchronize on the shared object being accessed. The problem with using String instances is mostly if some day someone uses a constant String as monitor object. Especially if the same constant string is used in different places as monitor object - to guard different unrelated critical sections.

  • @KuldeepYadav-jw7jn

    @KuldeepYadav-jw7jn

    3 жыл бұрын

    Yeah, got it, thank you 👍

  • @damukukandu8842
    @damukukandu88422 жыл бұрын

    is there a website where you can practice Multithreading?

  • @JakobJenkov

    @JakobJenkov

    2 жыл бұрын

    I don't know - but I would recommend you to install whatever language compiler you are trying to learn + and IDE, and get it to work on your own computer. You will learn more from that - than from practicing inside a website.

  • @journeytothedream6127
    @journeytothedream61273 жыл бұрын

    what about semphore! cant we use that instead of synchronised ?

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    Yes, a Semaphore can also be used, and also a Lock, or ReadWriteLock, as well as other constructs. The Synchronized block is just the most basic of them.

  • @journeytothedream6127

    @journeytothedream6127

    3 жыл бұрын

    @@JakobJenkov ❤️

  • @user-lw5ep2xn3u
    @user-lw5ep2xn3u2 жыл бұрын

    31:52 after removing synchronized block, the result remain the same(I printed the count variable in the inc method). I tested many times.

  • @JakobJenkov

    @JakobJenkov

    2 жыл бұрын

    I don't get the same results with and without synchronized blocks.

  • @user-lw5ep2xn3u

    @user-lw5ep2xn3u

    2 жыл бұрын

    @@JakobJenkov thanks for your reply, i tested many many many times,then i got the different result.

  • @tula1308
    @tula13082 жыл бұрын

    I disagree at 4:00 if I call setObj with thread1 I can also use thread 2 to call getObj at the time thread 1 is running

  • @JakobJenkov

    @JakobJenkov

    2 жыл бұрын

    Not at the exact same time. Since all the methods are synchronized at the object itself (this), then only 1 thread can enter any of these synchronized block at a time. All other thread must wait until no other thread is executing inside any of these synchronized blocks - before they can enter one of these blocks.

  • @leniedor733
    @leniedor7333 жыл бұрын

    So actually there's difference using ::: synchronized (this) {} and synchronized (ClassName.class) {} ??

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    Yes ! A big difference ! ... synchronized(this) {} synchronizes on the object, meaning only one thread at a time can enter a block synchronized on the same object - but if the threads access different objects of the same class, there is no problem. When you synchronize on the class object (synchronized(TheClass.class) {} ) - then it doesn't matter if the method belongs to an object, or if it is static - then only 1 thread can access that method at a time - because there is only one class object for a given class in the Java VM.

  • @leniedor733

    @leniedor733

    3 жыл бұрын

    @@JakobJenkov Simple explanation and clear. Thanks Jakov!

  • @prateekashtikar8631
    @prateekashtikar86312 жыл бұрын

    Could you please share code?

  • @JakobJenkov

    @JakobJenkov

    2 жыл бұрын

    All (or most, at least) of my Java code examples will be available in this GitHub repo (link below). There are more examples in the src/main/java directory than what are currently listed in the README.md file, so browse a bit around to see what's there! github.com/jjenkov/java-examples

  • @lucasrodriguesdelima8697
    @lucasrodriguesdelima86972 жыл бұрын

    I have been experimenting Java thread visibility problem with the popular example of sending a stop signal to the thread by means of a shared boolean and non-volatile variable and the target thread does not seem to get it) as below: public class ThreadVisibilityTest { //Shared variable to send a signal to the thread static boolean stopped = false; public static void main(String[] args) throws Exception { Thread targetThread = new Thread(new Runnable() { public void run() { while(!stopped) {} System.out.println("Target thread gets signal and stops..."); } }); targetThread.start(); TimeUnit.SECONDS.sleep(5); stopped=true; System.out.println("Main thread has sent stop signal to the thread..."); } } Main thread sends stop signal to the target thread after 5 seconds by means of setting stopped to true and the target thread can not get it and so does not stop. Defining stopped variable as volatile obviously solves the problem. Bu then I realized that if I make stopped variable non volatile but instead access it in a synchronized context in the target thread, target thread gets the final value and stops. So thread visibility problem seems to be solved just like using volatile. Thread targetThread = new Thread(new Runnable() { public void run() { while(true) { synchronized(this) { if(stopped) break; } } System.out.println("Target thread gets signal and stops..."); } }); And also the object monitor to be used for synchronization seems to have no effect as follows: synchronized(Thread.class) { if(stopped) break; }

  • @JakobJenkov

    @JakobJenkov

    2 жыл бұрын

    You could also create an explicit class for your Runnable, and have a "stop" field in that. That way you would be able to stop different threads individually, rather than stopping all the threads looking at your shared "stopped" variable.

  • @lucasrodriguesdelima8697

    @lucasrodriguesdelima8697

    2 жыл бұрын

    ​@@JakobJenkov In the above example I am reading it in synchronized context but not writing in the synchronized context. Even so, thread visibility problem seems to be solved just like using volatile. Is this something that happens by chance or do I miss something? I read your tutorial on synchronization and in it you say that there is no guarantee when the Thread will flush CPU registers to cache memory. In this example, did simply reading a synconized block (which could be empty) force the Thread that wrote the value to the variable - outside a synconized block, to flush the CPU registers to cached memory? That would be a different conclusion than many books and tutorials claim. Thanks for sharing it !! jenkov.com/tutorials/java-concurrency/synchronized.html

  • @prakritidevverma4315
    @prakritidevverma43153 жыл бұрын

    My head hurts now U guess too much synchronized with the word "synchronized"

  • @JakobJenkov

    @JakobJenkov

    3 жыл бұрын

    Hahaha :-D ... yes, it can be necessary to take a break once in a while to let new stuff sink in! I need that very often when I study new stuff myself :-) ... sometimes it almost feels as if I can feel the neurons making new connections inside my brain - that's how much stress it can put on my brain :-D

  • @prakritidevverma4315

    @prakritidevverma4315

    3 жыл бұрын

    @@JakobJenkov Its good to know that I am not alone. 😅😢

  • @prakritidevverma4315

    @prakritidevverma4315

    3 жыл бұрын

    @@JakobJenkov Do you have anything on spring boot thought ? I'm preparing you my interviews I don't see much of content worthy to watch for interviews. If you can recommend some material that would be great.

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

    very well explained but too slow. I'm sure that you can save 10 minutes or more

  • @JakobJenkov

    @JakobJenkov

    Жыл бұрын

    You can just increase video playback speed :-) Not all people are native English speakers, or understand things in the same speed, so it is hard to find a "perfect" explanation speed. Therefore, I tend to slow a bit down - because it's possible for faster learners to speed up playback :-)

  • @smejia6362

    @smejia6362

    Жыл бұрын

    @@JakobJenkov That advice is really working!! thanks!!

  • @trungpham7588
    @trungpham75883 жыл бұрын

    ...

  • @user-fp6lw9kc2y
    @user-fp6lw9kc2y11 ай бұрын

    is the reording of instructions take place inside a synchronized block? @JakobJenkov

  • @JakobJenkov

    @JakobJenkov

    9 ай бұрын

    That is possible, but instructions will not be reordered in any way that will alter the synchronization semantics of the whole synchronized block.

  • @tarunsingh7608
    @tarunsingh76085 күн бұрын

    The MOST Detailed Videos on Multi-threading & Concurrency in JAVA by PROFESSOR Synchronized, a.k.a, @JakobJenkov. These videos SYNC ur Brains on the Most recent concepts of Java threads as of Java 19 😃😃

  • @JakobJenkov

    @JakobJenkov

    5 күн бұрын

    Thank you very much for your kind and enthusiastic words 😊😊

Келесі