It may/will break. Example of execution:
- T1:
if(!cont.isLocked())
returns true - T2:
set(someObject)
- T1:
return cont.getObject();
returns an old version
Even worse, since you don't have a proper happens-before relationship between T2 and T1, cont.getObject()
may return the a reference to the new object created by T2, but pointing to an inconsistent/not-fully-constructed object.
You have a typical check-then-act problem.
Why don't you just use a volatile reference to your object?
public class Controller {
private volatile Object obj = new Object();
public Object get(){ return obj; }
public void set(Object o){ obj = o; }
}
That would be thread safe.