Wednesday, 21 August 2013

Ensuring initialization methods complete before member variable is accessed

Ensuring initialization methods complete before member variable is accessed

Is there a way of ensure that a set of methods operating on a volatile
static member variable via one thread will be done and over with before
other threads access this member variable? I am trying something like
this, but I am not sure if it would work.
public class MyClass {
private static final Object lock = new Object();
public static volatile MyObj mo; //assume null will be checked before
access
public static void initialize(Object something) {
if (mo == null) {
synchronized(lock) {
mo = new MyObj(something);
mo.doInit();
mo.doMoreInit();
}
}
}
}

No comments:

Post a Comment