Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of AtomicReference but without the volatile synchronization cost

Tags:

java

reference

What is the equivalent of:

AtomicReference<SomeClass> ref = new AtomicReference<SomeClass>( ... );

but without the synchronization cost. Note that I do want to wrap a reference inside another object.

I've looked at the classes extending the Reference abstract class but I'm a bit lost amongst all the choices.

I need something really simple, not weak nor phantom nor all the other references besides one. Which class should I use?

like image 356
NoozNooz42 Avatar asked Dec 01 '11 16:12

NoozNooz42


2 Answers

If you want a reference without thread safety you can use an array of one.

MyObject[] ref = { new MyObject() };
MyObject mo = ref[0];
ref[0] = n;
like image 154
Peter Lawrey Avatar answered Oct 16 '22 22:10

Peter Lawrey


If you are simply trying to store a reference in an object. Can't you create a class with a field, considering the field would be a strong reference that should achieve what you want

You shouldn't create a StrongReference class (because it would be silly) but to demonstrate it

public class StrongReference{
  Object refernece;

  public void set(Object ref){
    this.reference =ref;
  }
  public Object get(){
    return this.reference;
  }

}
like image 4
John Vint Avatar answered Oct 16 '22 23:10

John Vint