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 !
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.
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.👼
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.
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
Hi ... I wish I had a whole lot more time to make TH-cam 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!
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.
@@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?
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.
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.
@@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.
i dont get the part where u said volatile keyword makes the variable directly read or written from the memoty, and also makes the non volatile variable to be fetched from the main memory..is it like that
That is explained in more detail in other videos too. For instance, in my video about the Java Memory Model, the Java Happens Before Guarantee and Java Synchronized.
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.
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?
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.
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?
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.
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 :)
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
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.
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
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.
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...
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?
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 .
@@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.
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?
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.
@@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.
@@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; }
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.
@@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.
around 5:00, when hasNewObject is being read in the getObject method from the main memory, the thread hasn't yet come across this.object. So how will it be refreshed from main memory? In the setObject method, since hasNewObject method was being set after this.object was set, the thread had this.object. But in getObject it doesn't. How does that work?
The favorite part of this series of videos are those clear diagrams. They make the internal things clear and comprehensive.
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.
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 !
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.
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.👼
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.
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 😊
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
Thank you very much !! 😊
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.
Thanks :-)
Awesome demonstration and explanation Jakob!! Loved it!! keep up the good work!!
Thank you ! ... I will try to make more videos soon! :-)
Brilliant explanation with simple and easy to understand examples. Thanks a lot!
You are welcome! ... and thank you for taking the time to tell me! :-)
I always love your style to make all of things really simple
Thank you very much! :-) ... I do try hard to make the topics easy to understand! :-)
Another very cool and informative video on Java volatile keyword functionality. Thank you so much for making and posting this video!!
You are welcome :-)
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
Hi ... I wish I had a whole lot more time to make TH-cam 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!
Nice Explanations with a calm tone. Thank you.
You are welcome! :-)
This is an awesome video! Thank you so much for your detailed explanation. by far the clearest explanation I've seen on this topic.
Thank you very much :-)
I agree with the other comments. Very clear and simple explanation. Thank you!
Thank you very much, Hector :-)
Great tutorial really useful, super underrated channel.
Much appreciated! :-)
Thank you so much for such a concise and clear presentation! Please keep uploading such a great content!
You are welcome ! :-)
Another Superb Video with wonderful knowledge shared in detailed way.
Thank you so much Jakob :)
Thank you very much! :-) ... and you are welcome! :-)
Nicely explained, very helpful video. Thank you Jakob.
You are welcome! Glad you found it informative :-)
Clear explanations and perfect examples. Thx.
You are welcome! Glad it helped! :-)
Jakob :) you've decided to start videos. :) Thank you. I like your blog about java, read about 3 articles. Wish you luck!
Thank you ... but you should wish me "time" more than luck :-D
Thanks Jakob for the wonderful explanation .. :)
You are welcome! ... and thank you for letting me know :-)
Super cool explanations, thank you so much 👍
You are very welcome ! :-)
Thank you! Every good explanation
You are welcome ! :-)
I liked how you presented, thank you.
Thanks - glad you liked it :-)
thanks for this very clear explanation. SUBSCRIBED
You are welcome! :-)
Man , ur awesome , such great explaination , loved it.
Thanks - glad you liked it! :-)
Thank you, Jakob! But I have a question. Is it make sense to mark two or more variables as volatile in one class?
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.
@@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?
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.
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.
@@JakobJenkov
For myself I supposed all vars within visibility scope at the spot of "happening" (deals with volatile vars/synchronized blocks).
@@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.
Great explanation.
Thanks - glad you think so! :-)
Very nice, continue going on🔥
Thank you! :-)
i dont get the part where u said volatile keyword makes the variable directly read or written from the memoty, and also makes the non volatile variable to be fetched from the main memory..is it like that
That is explained in more detail in other videos too. For instance, in my video about the Java Memory Model, the Java Happens Before Guarantee and Java Synchronized.
How to make sure that a piece of code is executed by a single thread across multiple JVM instances (app deployed on multiple servers)?
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.
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?
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.
@@JakobJenkov Hi Jakob, Did you get the answers for your questions or still waiting!.. because I also want to know your question's answers.
@@JakobJenkov
Hello!
Have you done mentioned video about same-threaded concurrency approach/model?
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?
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.
Good explanation thank you
Thank you 😊
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 :)
The order should be reverse in the get and set methods.
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
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.
very clear explanation! thank you so much!
Your are welcome :-) Glad you found it helpful!
you deserve more views.
Thank you ! .... then I better make some more videos 😉
excellent tutorials, thanks
You are welcome! Glad you like them! :-)
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
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.
Best explanation
Thanks :-)
Hey JakoB great video, as always. A suggestion, I would highly apprecite if you could link the source material.
Many of my Java code examples can be found in this GitHub repository
github.com/jjenkov/java-examples
@@JakobJenkov Thank you. Are there any books that you refer to, before making theses videos.
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...
You should write the programs - as an exercise ;-)
great explanation!
Thank you! :-)
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?
My bad. The video answers my question at the 3-minute mark.
Great :-)
Awesome 👌
Thank you :-)
Please post the continuous video java. at least week ones ....
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!
so If our Threads run parallelly then using volatile won't help.. since exact same time thread might be accessing same volatile var
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 .
@@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.
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?
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.
@@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.
@@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;
}
Best !
Thanks :-)
I really don't understand what's the problem of count at the end of video
thank you! 😃
You're welcome 😊
thank you.
You're welcome !
setVal does getVal and getVal does setVal, hmm interesting if you know what I mean :-)
yeah what's going on there
perfecto
Thanks :-)
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.
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.
@@JakobJenkovOh It's Ok bro, you're doing a great job, Thanks 👍
so much overhead w volatile ffs..
volatile ffs?
@@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.
around 5:00, when hasNewObject is being read in the getObject method from the main memory, the thread hasn't yet come across this.object. So how will it be refreshed from main memory? In the setObject method, since hasNewObject method was being set after this.object was set, the thread had this.object. But in getObject it doesn't. How does that work?