0

Is it possible in Java to ensure that 'read' of the variable will give the value that was written to that variable exactly by the same thread ( in case of multiple concurrent 'write' actions ) ?

public class Client {
 private Config config;
 private RestClient client; 

 public void makeRequest() {
  client.post(config.getUrl(), requestEntity);
 }

 public void setConfig(Config config) {
  this.config = config; 
 }
}

I want to ensure that ' config.getUrl() ' will give me exactly the last value written to it ('url' variable of 'config' object') by the same thread some time ago ( config.setUrl("someUrl") 'happens before' config.getUrl() in the same thread ).

But it is possible that other threads will call config.setUrl("someOtherUrl") in the same time..

IhorK
  • 1
  • 3

1 Answers1

2

Use a ThreadLocal to store thread-specific values.

Have a look at ThreadLocals

For example you can use them like this:

ThreadLocal<String> threadLocalValue = new ThreadLocal<>();
// Set the value of the url for this thread.
threadLocalValue.set("someUrl");
// Fetch the value again later like this.
String someUrl = threadLocalValue.get();

The values you store in the ThreadLocal will only be available to that specific thread.