3

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?

2
  • 5
    AtomicReference might be a good choice, so you are guaranteed up-to-date reads on multiple threads. Commented Sep 7, 2016 at 21:24
  • Additionally, consider adding version field to instance of updatable data structure, so observers can detect if data was updated when they were looking at something else. Commented Sep 7, 2016 at 21:27

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

I went with that, though I feel a little guilty, since the thing I'm representing isn't strictly immutable (sometimes I modify it, sometimes I want to replace it)
@EdwardPeters so what? The pointer pointer part will work. If your object is mutable and you're working with a multi-threaded environment, you'll need to handle concurrency there too. You may consider using AtomicReference for your class's mutable fields too.
@Bohemian Yeah, I synchronized on it, but the documentation I read for AtomicReference said "Immutable" a lot, so I'm worried I might be breaking a contract somewhere.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.