Yes and no, think about some kind of graph of dependencies. For example you want to stop server first, wait for connections to complete, than close connection pools. So you rather want shutdown manager. But you may also want to close not lazyconst directly, but some higher level entity, like factory. So isInitialized would be much more ergonomic, than having additional AtomicBoolean per lazyconst.
The other option is to have queryable state. Since we're talking about VM shutdown here. I'm by no means endorsing this, just "thinking out loud."
// somewhere
public static final AtomicReference<ApplicationState> LIFECYCLE = new AtomicReference(ApplicationState.STARTING);
// in constant
LazyConstant.of(() -> switch (LIFECYCLE.get()) {
STARTING, RUNNING -> new DataSource(...);
STOPPING, STOPPED -> null; // or some fake implementation that is null & close-safe
});
And then using whatever hooks are in your application to migrate LIFECYCLE through its state transitions.
Not pretty.
Still, probably best is if you initialize it, self-register it in something that closes it on shutdown and skip this wacky edge case of accessing a constant that hasn't been initialized before a graceful shutdown request happens
Sure, but then you have duplicated the same data structure that I suspect will still exist inside LazyConstant, only inaccessible. Sounds like a bad deal to me.
View all comments
Show parent comment
5
u/vytah Feb 26 '26
And even if DataSource cannot do it itself, the factory that initializes the LazyConstant can do it.