Method1
I can think of a listener class.
Constructor () { object = null listener = new Object() { // this is called once object = init() listener = new Object() { // next time do-nothing() // this is called } } Object get() { listener.invoke() return object
This has no status checks, but it adds an extra field for each object, effectively duplicating memory consumption, while the stupid punishment of calling useless listener.invoke()
code is preserved. I do not know how to remove it with all the polymorphism. Since the get()
method is used by all instances of the class, it cannot be changed.
Method2
On-demand Java initialization using lazy class loading.
Bottom row
So, it seems that alternatives are worse than conditional, because modern processors optimize branch forecasts. Thus, the penalty check will be very tiny, I expect as soon as the code is initialized, and the branch always goes in one direction. A fake branch will only be accepted once during initialization, and it will also be short compared to your initialization time. Otherwise, you may not want to delay initialization.
Val
source share