I have a situation I've run into a couple of times, where multiple classes from different parts of the architecture want to be looking at the same data structure, which may be entirely replaced (for instance, when a newer version comes from the network.) If I keep the data structure and update the information that's easy enough (everything can reference the same one, and will get the up-to-date info when they look), but if the reference is re-assigned entirely, that isn't reflected elsewhere.
I had an idea to make a super-generic wrapper like:
public class Wrapper<T>{
public T _value;
}
With the idea that you would never re-assign the wrapper, just the value inside it. All the different components could then point to the wrapper, and the inner value could be re-assigned cleanly when a "new" version came along. (I think I've seen this done with ** in C.)
But, I'm suspicious that I've never seen this before. Is there a better way to address this problem?
Use AtomicReference.
String initialReference = "initial value referenced";
AtomicReference<String> atomicStringReference =
new AtomicReference<String>(initialReference);
String newReference = "new value referenced";
//directly update
atomicReference.set(newReference);
//compare and set
boolean exchanged = atomicStringReference.compareAndSet(initialReference, newReference);
System.out.println("exchanged: " + exchanged);
exchanged = atomicStringReference.compareAndSet(initialReference, newReference);
System.out.println("exchanged: " + exchanged);
//get value
String reference = atomicReference.get();
Code example from here
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