In Java, when we want to ensure that compiler should not do optimization by keeping a local copy of a variable, then we make the variable volatile. Using the variable as volatile ensures that the threads would not use a local copy of the variable but they would use the variable as it is stored in the main memory. But, does it mean that the volatile variable is thread-safe? Also how does it differ in case of a primitive type and in case we use a user defined object?
Share
volatilemeans that the value will always be fresh; if another thread put a new object into the variable before you, you will see that object.It does not change the behavior of the value; you cannot magically make an object thread-safe.