Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does changing a volatile field update the object?

I have the following class

public class Guardian {
    volatile String response;
    private Future future;
    private Long time;
}

If response was to be modified by thread A, then would thread B see the new value of response via:

Guardian guardian = requestManager.getGuardian();
String response = guardian.getResponse();
like image 714
user3809938 Avatar asked Mar 04 '26 00:03

user3809938


2 Answers

Assuming that you are aware that string is immutable then yes, the volatile keyword gives you the guaranty that thread B will get the last value of response no matter on which thread that did happen.

like image 181
ΦXocę 웃 Пepeúpa ツ Avatar answered Mar 06 '26 13:03

ΦXocę 웃 Пepeúpa ツ


The volatile keyword prevents a variable from being cached in thread local memory. What it prevents is false positives because your variable has been changed in the main memory but that change hasn't been reflected in local cache memory.

Your example would be subject to a Race condition because it would depend on the time taken for each of the threads to execute their relevant operations, but assuming that isn't a problem, then yes, you would get the latest version of that variable in the JVM because it was not cached in thread local memory.

like image 42
christopher Avatar answered Mar 06 '26 13:03

christopher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!