I've read all about how double checked locking fixes never work and I don't like lazy initialization, but it would be nice to be able to fix legacy code and such a problem is too enticing not to try to solve.
Here is my example: private int timesSafelyGotten = 0; private Helper helper = null;
public getHelper()
{
if (timesSafelyGotten < 1) {
synchronized (this) {
if (helper == null) {
helper = new Helper();
} else {
timesSafelyGotten++;
}
}
}
return helper;
}
This way the synchronized code must run once to create the helper and once when it is gotten for the first time so theoretically timesSafelyGotten cannot be incremented until after the synchronized code which created the helper has released the lock and the helper must be finished initializing.
I see no problems, but it is so simple it seems too good to be true, what do you think?
Caleb James DeLisle