Since I'm working on a server with absolutely no non-persisted state for users, every User-related object we have is rolled out on every request.
Consequently I often find myself doing lazy initialization of properties of objects that may go unused.
protected EventDispatcher dispatcher = new EventDispatcher();
Becomes…
protected EventDispatcher<EventMessage> dispatcher;
public EventDispatcher<EventMessage> getEventDispatcher() {
if (dispatcher == null) {
dispatcher = new EventDispatcher<EventMessage>();
}
return dispatcher;
}
Is there any reason this couldn't be built into Java?
protected lazy EventDispatcher dispatcher = new EventDispatcher();
As mentioned below in the comments, I realize a language could theoretically evolve to include most anything you want. I'm looking for a practical measurement of possibility. Would this conflict with other features? Is the implementation simple enough to work well with the JVM as it exists? And even, is it a good idea?
Best Answer
Here is an eight page answer to your question: http://tinlizzie.org/~awarth/papers/fool07.pdf
If i can try and coarsely summarize the problems with adding laziness, it's the corner cases. There are a lot of caveats around side-effects. Consider, in your example, if the constructor had visible side-effects like bumping a global counter or doing I/O... It's hard to reason about when that would happen. Or consider even uglier side-effects about exceptions (they're thrown ... when you reference the lazy object?)
Just skip to section 6 in the above paper. (And admire all the type system formal logic on the pages you skip ...)