I’m just thinking out load here but if someone has an authoritive answer that’d rock too.
It’s not too uncomon to see code for lazy initilization that at the start of a common public method you test a boolean and possibly initilize the rest of an object. eg:
class Foo {
boolean initilized = false;
publc void doSomething() {
if (!initilized) doInit();
// Other work
}
private void doInit() {
// Some stuff
initilized = true;
}
}
threading issues and correctness aside, the above code is a little error prone because as I add new methods I have to remeber to include that whole if statement and method call.
Slightly more robust is the code below:
class Foo {
boolean initilized = false;
publc void doSomething() {
doInit();
// Other work
}
private void doInit() {
if (initilized) return;
// Some stuff
initilized = true;
}
}
In this case the “if (initilized)” is in the doInit() method and I don’t have to worry about when it is called. But now every time I call doSomething() I incur the overhead of calling doInit() even if it immeaditly returns.
Is it possible for HotSpot to optimize the “if (initilized)” to just before the method call? Is it worth the time and effort?