Java Volatile

  Рет қаралды 43,153

Jakob Jenkov

Jakob Jenkov

Күн бұрын

The Java volatile keyword can be applied to Java variable declarations to force the Java VM to always read the variable value directly from main memory, and always write changes to the variable directly back to main memory immediately.
Chapters
0:00 Java volatile introduction
0:41 Non-volatile variable visibility problems
2:27 Java volatile visibility guarantee
5:30 Instruction reordering could break the Java volatile visibility guarantee
12:33 Java volatile happens before guarantee
15:03 Java volatile performance overhead
15:56 Java volatile is not always enough
Java Memory Model - JSR 133
www.cs.umd.edu/~pugh/java/mem...
Java volatile tutorial - textual:
tutorials.jenkov.com/java-conc...
Java synchronized tutorial - textual / video:
tutorials.jenkov.com/java-conc...
• Java Synchronized - Th...
Java concurrency tutorial - textual:
tutorials.jenkov.com/java-conc...
Java concurrency tutorial - playlist:
• Java Concurrency and M...

Пікірлер: 125
@user-rc8rv4sk2j
@user-rc8rv4sk2j 3 жыл бұрын
The favorite part of this series of videos are those clear diagrams. They make the internal things clear and comprehensive.
@JakobJenkov
@JakobJenkov 3 жыл бұрын
I am happy you like those diagrams! It actually takes me some time to figure out how to illustrate the points in the clearest way.
@omnipoten8
@omnipoten8 3 жыл бұрын
Again, the best explanation I have ever seen about volatile keyword in Java. As clear and concise as it can be . No loopholes, no smart fancy tech words to confuse the meaning, but just a clear cut explanation. I have infact wrote down the key sentences from this video in my notes :) . Once again you nailed it Jakob !
@JakobJenkov
@JakobJenkov 3 жыл бұрын
Hi Vishal, I am happy you feel that way :-) ... I've had my share of hard time trying to understand many advanced concepts - often because the descriptions were hard to understand.
@sujeetbadnale9441
@sujeetbadnale9441 6 ай бұрын
Thank you@@JakobJenkov, for making saving us from the hardships that you have gone through. Indeed you are blessed and now are being blessing for us. God Bless You. Continue to be a blessing for all of us.👼
@shubhamagarwal1434
@shubhamagarwal1434 Ай бұрын
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 Ай бұрын
Thanks :-)
@repotek
@repotek 10 ай бұрын
That was super clear. As long as you deliver this concept very smoothly, then you understand it very well. which is very rare this days.
@JakobJenkov
@JakobJenkov 10 ай бұрын
Great to hear it was clear !! That's what I am trying to do - to make sure each video presents its topic as clearly as possible 😊
@Abdullahkhan-ks2py
@Abdullahkhan-ks2py Жыл бұрын
Thank you so much for this video. I was always confused with volatile and this video has cleared all my doubts. True java champion!! Thanks
@JakobJenkov
@JakobJenkov Жыл бұрын
Thank you very much !! 😊
@ajaygaulia1767
@ajaygaulia1767 Жыл бұрын
Awesome demonstration and explanation Jakob!! Loved it!! keep up the good work!!
@JakobJenkov
@JakobJenkov Жыл бұрын
Thank you ! ... I will try to make more videos soon! :-)
@VLADICA94KG
@VLADICA94KG 3 жыл бұрын
Thank you so much for such a concise and clear presentation! Please keep uploading such a great content!
@JakobJenkov
@JakobJenkov 3 жыл бұрын
You are welcome ! :-)
@farhadpagdiwala4458
@farhadpagdiwala4458 2 жыл бұрын
Another very cool and informative video on Java volatile keyword functionality. Thank you so much for making and posting this video!!
@JakobJenkov
@JakobJenkov 2 жыл бұрын
You are welcome :-)
@user-hg2pf1hs4z
@user-hg2pf1hs4z 3 жыл бұрын
I always love your style to make all of things really simple
@JakobJenkov
@JakobJenkov 3 жыл бұрын
Thank you very much! :-) ... I do try hard to make the topics easy to understand! :-)
@jkwong6167
@jkwong6167 2 жыл бұрын
Brilliant explanation with simple and easy to understand examples. Thanks a lot!
@JakobJenkov
@JakobJenkov 2 жыл бұрын
You are welcome! ... and thank you for taking the time to tell me! :-)
@susanwowe7810
@susanwowe7810 3 жыл бұрын
Nice Explanations with a calm tone. Thank you.
@JakobJenkov
@JakobJenkov 3 жыл бұрын
You are welcome! :-)
@alexwhb122
@alexwhb122 3 жыл бұрын
This is an awesome video! Thank you so much for your detailed explanation. by far the clearest explanation I've seen on this topic.
@JakobJenkov
@JakobJenkov 3 жыл бұрын
Thank you very much :-)
@joeyzhao1596
@joeyzhao1596 3 жыл бұрын
Clear explanations and perfect examples. Thx.
@JakobJenkov
@JakobJenkov 3 жыл бұрын
You are welcome! Glad it helped! :-)
@nitinpandey2859
@nitinpandey2859 3 жыл бұрын
Nicely explained, very helpful video. Thank you Jakob.
@JakobJenkov
@JakobJenkov 3 жыл бұрын
You are welcome! Glad you found it informative :-)
@theunusual4566
@theunusual4566 2 жыл бұрын
Another Superb Video with wonderful knowledge shared in detailed way. Thank you so much Jakob :)
@JakobJenkov
@JakobJenkov 2 жыл бұрын
Thank you very much! :-) ... and you are welcome! :-)
@crazy-boy6143
@crazy-boy6143 2 жыл бұрын
I hit the like button and subscribed, so I hope new videos will come out before I finish those 22 videos. Thanks for those awesome videos, I really appreciate it
@JakobJenkov
@JakobJenkov 2 жыл бұрын
Hi ... I wish I had a whole lot more time to make KZbin videos :-) ... but my time is a bit limited these days. I still plan to release videos on a continual basis - but christmas and new years was pretty busy for me!
@ffatheranderson
@ffatheranderson 3 жыл бұрын
Jakob :) you've decided to start videos. :) Thank you. I like your blog about java, read about 3 articles. Wish you luck!
@JakobJenkov
@JakobJenkov 3 жыл бұрын
Thank you ... but you should wish me "time" more than luck :-D
@hectorrios1432
@hectorrios1432 Жыл бұрын
I agree with the other comments. Very clear and simple explanation. Thank you!
@JakobJenkov
@JakobJenkov Жыл бұрын
Thank you very much, Hector :-)
@rohalkurup3063
@rohalkurup3063 Жыл бұрын
Thanks Jakob for the wonderful explanation .. :)
@JakobJenkov
@JakobJenkov Жыл бұрын
You are welcome! ... and thank you for letting me know :-)
@SosetaFurioasaJr
@SosetaFurioasaJr 3 жыл бұрын
I liked how you presented, thank you.
@JakobJenkov
@JakobJenkov 3 жыл бұрын
Thanks - glad you liked it :-)
@IdeeFixeGamer
@IdeeFixeGamer 3 жыл бұрын
Great tutorial really useful, super underrated channel.
@JakobJenkov
@JakobJenkov 3 жыл бұрын
Much appreciated! :-)
@gtian8669
@gtian8669 3 жыл бұрын
very clear explanation! thank you so much!
@JakobJenkov
@JakobJenkov 3 жыл бұрын
Your are welcome :-) Glad you found it helpful!
@oleksandr3275
@oleksandr3275 8 ай бұрын
Super cool explanations, thank you so much 👍
@JakobJenkov
@JakobJenkov 8 ай бұрын
You are very welcome ! :-)
@BD-mc7lc
@BD-mc7lc 7 ай бұрын
Thank you! Every good explanation
@JakobJenkov
@JakobJenkov 7 ай бұрын
You are welcome ! :-)
@fannyfan1742
@fannyfan1742 3 жыл бұрын
thanks for this very clear explanation. SUBSCRIBED
@JakobJenkov
@JakobJenkov 3 жыл бұрын
You are welcome! :-)
@nikkipik3411
@nikkipik3411 3 жыл бұрын
Man , ur awesome , such great explaination , loved it.
@JakobJenkov
@JakobJenkov 3 жыл бұрын
Thanks - glad you liked it! :-)
@gparashar4u
@gparashar4u 3 жыл бұрын
Great explanation.
@JakobJenkov
@JakobJenkov 3 жыл бұрын
Thanks - glad you think so! :-)
@romanburenko7593
@romanburenko7593 3 жыл бұрын
great explanation!
@JakobJenkov
@JakobJenkov 3 жыл бұрын
Thank you! :-)
@SoeaOu
@SoeaOu 2 жыл бұрын
excellent tutorials, thanks
@JakobJenkov
@JakobJenkov 2 жыл бұрын
You are welcome! Glad you like them! :-)
@lifesport1380
@lifesport1380 2 жыл бұрын
Very nice, continue going on🔥
@JakobJenkov
@JakobJenkov 2 жыл бұрын
Thank you! :-)
@husohomeful
@husohomeful 3 жыл бұрын
you deserve more views.
@JakobJenkov
@JakobJenkov 3 жыл бұрын
Thank you ! .... then I better make some more videos 😉
@user-sb4jr9rg4q
@user-sb4jr9rg4q Жыл бұрын
Good explanation thank you
@JakobJenkov
@JakobJenkov Жыл бұрын
Thank you 😊
@jonneyjonney8942
@jonneyjonney8942 Жыл бұрын
Awesome 👌
@JakobJenkov
@JakobJenkov Жыл бұрын
Thank you :-)
@AtiqurRahman-gj6mg
@AtiqurRahman-gj6mg 3 жыл бұрын
Best explanation
@JakobJenkov
@JakobJenkov 3 жыл бұрын
Thanks :-)
@garimadhanania1853
@garimadhanania1853 2 ай бұрын
thank you! 😃
@JakobJenkov
@JakobJenkov 2 ай бұрын
You're welcome 😊
@Khrystyable
@Khrystyable 3 жыл бұрын
Thank you, Jakob! But I have a question. Is it make sense to mark two or more variables as volatile in one class?
@JakobJenkov
@JakobJenkov 3 жыл бұрын
That depends on how you access these two variables from different threads. If they are accessed separately, then yes. If they are always accessed together, first A then B, then it probably doesn't make as much sense.
@MahfuzurRahman-xl9pj
@MahfuzurRahman-xl9pj Жыл бұрын
@@JakobJenkov I have follow up question. Suppose variable A and B are access together by a thread and made both the variables volatile, is there any performance overhead?
@vincool5507
@vincool5507 3 жыл бұрын
Great video and nicely explained. One question though : When you say " all variables visible to thread at the time of volatile read/write" , When is a variable considered VISIBLE to a thread.
@JakobJenkov
@JakobJenkov 3 жыл бұрын
You are welcome :-) Regarding your question - I have myself been looking for the exact definition of what "variables visible to a thread" means - but I have not yet found a 100% precise definition. I assume that it at least means all variables accessed from within a given synchronized block, or inside a method that accesses a volatile variable. Possibly all member variables within the current class. Possibly even variables further up the call stack.
@manOfPlanetEarth
@manOfPlanetEarth 2 жыл бұрын
@@JakobJenkov For myself I supposed all vars within visibility scope at the spot of "happening" (deals with volatile vars/synchronized blocks).
@jayeshghule1
@jayeshghule1 7 ай бұрын
@@JakobJenkovI appreciate the explanation, but honestly I did'nt understood what visible variables to the thread means , if we are not sure what "variable visible to thread" specifically means, then how can you suggest that don't use volatile for two variables that are together, or moved outside and up to the synchronized block. Ideally the best practice is to make all of them volatile when we expect guaranteed visibility because we never know what will happen for sure.
@ehabahmedyassen
@ehabahmedyassen Жыл бұрын
Hi Jakob, thank you so much for the amazing concurrency tutorial :) I have learned a lot from your course till now and still have about 17 lectures to go. I have a question/suggestion about the given example in this lecture. As I understand, Thread-1 is meant to execute the setter method and demonstrate the benefit of having the volatile variable "int val3" being written to at the end of the method "final instruction" and that this will force the program to write the other 2 variables to the main memory as well as val3. However, i think this example is mixing things a bit because in the setValues method, we are reading values in a different order from the order suggested in the getValues method. I'd like to know how do you see it from this point of view. Thanks in advance :)
@JakobJenkov
@JakobJenkov Жыл бұрын
The order should be reverse in the get and set methods.
@SahilRallySuperStar
@SahilRallySuperStar 3 жыл бұрын
Best !
@JakobJenkov
@JakobJenkov 3 жыл бұрын
Thanks :-)
@alienmatrix235
@alienmatrix235 3 жыл бұрын
Great video! I have a question about non volatile variables being flushed to/ read from when a volatile variable is read / written to. Is this a side effect of the size of the CPUs cache lines? Or does the JVM specifically guarantee that all visible variables will be read from / flush to main memory? For example, say we have 64 byte cache lines, but a class has 100 fields (more than what would fit into a single cache line). If the 100th field is volatile and I write to it, will all 100 fields be flushed to main memory? Or only the n closest fields that can fit in the cache line?
@JakobJenkov
@JakobJenkov 3 жыл бұрын
That's a very good question! I have only been able to find a description saying that "all variables *visible* to the thread are flushed..." , but I have not been able to find a precise definition of what "visible" means, unfortunately. Is it only the variables accessible from inside the method that accesses the volatile variable? Or does it also include member variables / static variables inside the class contaning the method? And what about variables "visible" further up the call stack of the same thread? To be on the safe side, I consider "visibility" to be narrow - meaning parameters and local variables of the method accessing the volatile variable + member variables in the same class. Questions like these is why I prefer a single-threaded / same-threaded concurrency model - similar to what is used in Node.JS . I will be making a video about this type of concurrency model soon. Then you have a lot less concurrency issues to deal with.
@rajasekharb7901
@rajasekharb7901 2 жыл бұрын
@@JakobJenkov Hi Jakob, Did you get the answers for your questions or still waiting!.. because I also want to know your question's answers.
@manOfPlanetEarth
@manOfPlanetEarth 2 жыл бұрын
@@JakobJenkov Hello! Have you done mentioned video about same-threaded concurrency approach/model?
@minasalah8210
@minasalah8210 3 жыл бұрын
thank you.
@JakobJenkov
@JakobJenkov 3 жыл бұрын
You're welcome !
@rishavmasih9450
@rishavmasih9450 Жыл бұрын
Hey JakoB great video, as always. A suggestion, I would highly apprecite if you could link the source material.
@JakobJenkov
@JakobJenkov Жыл бұрын
Many of my Java code examples can be found in this GitHub repository github.com/jjenkov/java-examples
@rishavmasih9450
@rishavmasih9450 Жыл бұрын
@@JakobJenkov Thank you. Are there any books that you refer to, before making theses videos.
@iwebappe7981
@iwebappe7981 2 жыл бұрын
Thanks for the video, I got a question please When you say, threads will read variables from the main memory, you mean from the JVM heap right? this sounds logic for reference type objects where the objects inside the threads stacks will point to the JVM heap so if you modify the object inside the heap, the references inside stacks will point to the new object but for primitive types, values are directly stored inside stacks, there's no track of them inside the heap so how come you speak about Main memory in this case? does this mean that when we declare a primitive variable as volatile it will be stored in the heap instead of each thread stack? I appreciate it a lot if you could explain this point
@JakobJenkov
@JakobJenkov 2 жыл бұрын
No - by "main memory" I mean RAM. Both the thread stacks and the heap are kept in RAM - and then replicated up through the L3, L2 and L1 caches on their way to the CPU registers - when used. The concepts of the [CPU registers, L1, L2, L3 caches] and the [Thread stacks + Java VM Heap] are orthogonal concepts.
@bunthaideng2492
@bunthaideng2492 6 ай бұрын
Really appreciate your tutorial. seems the volatile is not for thread-safe, is it a better to use the synchronized (read/write) rather than the volatile?
@JakobJenkov
@JakobJenkov 6 ай бұрын
It depends on the situation. If you just need other threads to be able to read what one thread writes, then in some cases it is enough with volatile... but it depends.
@AllInOne-jg5qx
@AllInOne-jg5qx 3 жыл бұрын
That was the good Explanation. But the thing is you should have also written the programs and executed them for better understanding. I can understand that your video was being too long. But there should be a part 2 of this video...
@JakobJenkov
@JakobJenkov 3 жыл бұрын
You should write the programs - as an exercise ;-)
@bhumikasingh850
@bhumikasingh850 3 жыл бұрын
How to make sure that a piece of code is executed by a single thread across multiple JVM instances (app deployed on multiple servers)?
@JakobJenkov
@JakobJenkov 3 жыл бұрын
That is a much harder task. Some early implementations used a database lock in a database shared by all the JVMs. You would probably have to use something similar to that.
@user-uc5iv5gf5u
@user-uc5iv5gf5u 9 ай бұрын
I've got a question to a diagram on 13:30. Does having only val3 as volatile variable (not all three) guarantees the stableness of visibility rule? I mean, the thread interruption may happen after the assignment of this.val2 in setValues method (because no synchronized keyword here). In this case, getValues will read incorrect values from main memory because the changes weren't pushed to main memory (because thread interruption occured before assignment to volatile variable). Correct me, if I'm wrong
@JakobJenkov
@JakobJenkov 8 ай бұрын
If the thread interruption happens after assignment of val2, not thread visibility is guaranteed. What I am saying is - that once val3 has been set, the fact that val3 is volatile means that thread visibility also kicks in for val2 and val1 too.
@sureshkct
@sureshkct 3 жыл бұрын
Please post the continuous video java. at least week ones ....
@JakobJenkov
@JakobJenkov 3 жыл бұрын
I will try to post as often as I can! ... but it's sometimes hard to find the time after work :-) But I will try!
@adil-hussain-84
@adil-hussain-84 3 жыл бұрын
In the first example, why is the 'object' property not marked as 'volatile' also? In the absence of the 'volatile' keyword, do we not run the risk of referencing a stale object on line 17?
@adil-hussain-84
@adil-hussain-84 3 жыл бұрын
My bad. The video answers my question at the 3-minute mark.
@JakobJenkov
@JakobJenkov 3 жыл бұрын
Great :-)
@islombekmamatqulov7821
@islombekmamatqulov7821 Жыл бұрын
perfecto
@JakobJenkov
@JakobJenkov Жыл бұрын
Thanks :-)
@danishrockz1
@danishrockz1 2 жыл бұрын
so If our Threads run parallelly then using volatile won't help.. since exact same time thread might be accessing same volatile var
@JakobJenkov
@JakobJenkov 2 жыл бұрын
If both threads read and write the same volatile variable - they have to be quite careful to avoid race conditions - yes. However, if one thread only writes to the volatile variable, and the other thread only reads it - then it will work. This situation is also known as single-writer-single-reader - or - single-reader-single-writer .
@manOfPlanetEarth
@manOfPlanetEarth 2 жыл бұрын
@@JakobJenkov many threads can write volatile at the same moment. Note: if it is "one touch" writing: you do not need firstly read then modify it then write, a thread just puts his value and runs away:) It's ok for volatile.
@ultimatewarriorfrieza275
@ultimatewarriorfrieza275 3 жыл бұрын
I declared a class with a volatile boolean variable with an initial value of true. Created 4 threads which run 3 statements Print the variable Change it to false And print again When I started the 4 threads, I expect 8 lines of output and that whenever i see a false appear for the first time, the next statements must follow suit. But that isn't the case with my results. How was that happening?
@JakobJenkov
@JakobJenkov 3 жыл бұрын
Do all threads share the same instance of that class you created? Or do they have each their own instance of that class? Only if the instance is shared between all threads will you get the expected behaviour.
@ultimatewarriorfrieza275
@ultimatewarriorfrieza275 3 жыл бұрын
@@JakobJenkov it does, all threads run through this variable. I tried it and I expected that the first time I see false all the remaining statements should return false but it has not.
@ultimatewarriorfrieza275
@ultimatewarriorfrieza275 3 жыл бұрын
@@JakobJenkov public class Sample{ public static void main(String... args){ A a = new A() ; Runnable r = new Runnable() { public void run() { System.out.println(a.flag); a.flag=false; System.out.println(a.flag); } } ; Thread t1 = new Thread(r); Thread t2 = new Thread(r); Thread t3 = new Thread(r); Thread t4 = new Thread(r); t1.start(); t2.start(); t3.start(); t4.start(); } } class A{ volatile boolean flag = true; }
@sihanadi5149
@sihanadi5149 Жыл бұрын
I really don't understand what's the problem of count at the end of video
@loki549
@loki549 Жыл бұрын
Thank you! And I also want to ask you to talk a bit more clearly, because I'm not a native speaker, and sometimes it's hard to understand you.
@JakobJenkov
@JakobJenkov Жыл бұрын
I am also not a native English speaker. I am already trying to speak as clearly as I can - so I am not sure I can do any better without speaking incredibly slowly. But - there are already others complaining that I speak too slowly, so I will probably not slow too much down.
@loki549
@loki549 Жыл бұрын
@@JakobJenkovOh It's Ok bro, you're doing a great job, Thanks 👍
@emil8367
@emil8367 2 жыл бұрын
setVal does getVal and getVal does setVal, hmm interesting if you know what I mean :-)
@smithcodes1243
@smithcodes1243 2 жыл бұрын
yeah what's going on there
@-boiadeiro-
@-boiadeiro- 3 жыл бұрын
so much overhead w volatile ffs..
@JakobJenkov
@JakobJenkov 3 жыл бұрын
volatile ffs?
@smithcodes1243
@smithcodes1243 2 жыл бұрын
@@JakobJenkov ffs = for fuck's sake, he is basically annoyed with how much extra work and things we have to consider when using volatile keyword in java.
CPU Cache Coherence + Java Concurrency
5:01
Jakob Jenkov
Рет қаралды 17 М.
The Java Memory Model - The Basics
23:41
Jakob Jenkov
Рет қаралды 120 М.
MEU IRMÃO FICOU FAMOSO
00:52
Matheus Kriwat
Рет қаралды 38 МЛН
ОСКАР ИСПОРТИЛ ДЖОНИ ЖИЗНЬ 😢 @lenta_com
01:01
бесит старшая сестра!? #роблокс #анимация #мем
00:58
КРУТОЙ ПАПА на
Рет қаралды 3,2 МЛН
Tom & Jerry !! 😂😂
00:59
Tibo InShape
Рет қаралды 59 МЛН
Java Happens Before Guarantee - Java Memory Model - Part 2
26:13
Jakob Jenkov
Рет қаралды 54 М.
How to use the volatile keyword in C?
6:48
Jacob Sorber
Рет қаралды 68 М.
Java Lock
28:51
Jakob Jenkov
Рет қаралды 43 М.
Compare and Swap in Java
24:21
Jakob Jenkov
Рет қаралды 15 М.
Урок Java 346: Volatile и happens before
18:16
Уроки Java
Рет қаралды 11 М.
Thread Signaling in Java
23:26
Jakob Jenkov
Рет қаралды 10 М.
ИГРОВОВЫЙ НОУТ ASUS ЗА 57 тысяч
25:33
Ремонтяш
Рет қаралды 296 М.
Low Price Best 👌 China Mobile 📱
0:42
Tech Official
Рет қаралды 718 М.
После ввода кода - протирайте панель
0:18
Хотела заскамить на Айфон!😱📱(@gertieinar)
0:21
Взрывная История
Рет қаралды 4,6 МЛН
YOTAPHONE 2 - СПУСТЯ 10 ЛЕТ
15:13
ЗЕ МАККЕРС
Рет қаралды 142 М.