Help the world stop coronavirus! Stay home!

Prev Next

Java / volatile

What guarantee volatile variable provides? (OR) The Java volatile Happens-Before Guarantee

Since Java 5 the volatile keyword guarantees more than just the reading from and writing to main memory of variables.

If Thread A writes to a volatile variable and Thread B subsequently reads the same volatile variable, then all variables visible to Thread A before writing the volatile variable, will also be visible to Thread B after it has read the volatile variable.

Developers may use this extended visibility guarantee to optimize the visibility of variables between threads. Instead of declaring each and every variable volatile, only one or a few need be declared volatile.

Thread A:

   sharedObject.myNonVolatileVar = 123;
    sharedObject.myVolatileVar     = sharedObject.myVolatileVar + 1;

Thread B:

  int myVolatileVar     = sharedObject.myVolatileVar;
    int myNonVolatileVar = sharedObject.myNonVolatileVar;

❤Cash Back At Stores you Love !!!❤

Earn your $10 reward when you make your first purchase through Ebates by signing up with clicking below button.

Ebates Coupons and Cash Back

More Related questions...

Show more question and Answers...

Java ThreadLocal

Comments & Discussions