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();
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With