I have just had a use-case for a resettable variation of @Getter(lazy=true)!
It comes up when you want to have central collection XXXProviderIndex-something, possible obtained from a ServiceLoader per default, possible decorated upon by using Jakarta CDI or Spring DI, depending upon context. Then make a list of default suppliers, possibly decorate these with additional suppliers, possibly wipe the list clean and insert context-specific supplier. Then you ask for the supplied list -- on-demand, lazy to resolve what should be the static list to be used during the application lifetime.
Then you come too late -- the list is set before you have had a chance to modify the suppliers. Then you really want to reset the list.
What is can be boiled down to -- within a larger context --
https://github.com/sabroe/Topp-Standard/tree/main/module/Core/Topp-Standard-Loader-Library/src/main/java/com/yelstream/topp/standard/load/util/holder-- is this:
public interface Container<X> {
X getItem();
}
@AllArgsConstructor(staticName="of")
final class LazyContainer<X> implements Container<X> {
private final Supplier<X> itemSupplier;
@Getter(lazy=true)
private final X item=itemSupplier.get();
}
public interface ResettableContainer<X> extends Container<X> {
void reset();
}
@AllArgsConstructor(staticName="of")
final class ResettableLazyContainer<X> implements ResettableContainer<X> {
private final Supplier<X> itemSupplier;
private final AtomicReference<X> itemHolder=new AtomicReference<>();
@Override
public X getItem() {
X item=itemHolder.get();
if (item==null) {
synchronized (itemHolder) {
item=itemHolder.updateAndGet(v->v!=null?v:itemSupplier.get());
}
}
return item;
}
@Override
public void reset() {
synchronized (itemHolder) {
itemHolder.set(null);
}
}
}
THE POINT being that to get a "occationally resettable" version, we have to create code that essentially ends up replicating the complete code generated by @Getter(lazy=true)!
Hence, there could be a point with a version like
@Getter(lazy=true,resettable=true)
While LazyContainer relies fully on Lombok, ResettableLazyContainer is my own code.
Kind regards,
Morten Sabroe Mortensen