com.ulisesbocchio.jasyptspringboot.util.Singleton Maven / Gradle / Ivy
package com.ulisesbocchio.jasyptspringboot.util;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* Singleton initializer class that uses an internal supplier to supply the singleton instance. The supplier
* originally checks whether the instanceSupplier
* has been initialized or not, but after initialization the instance supplier is changed to avoid extra logic
* execution.
*/
public final class Singleton implements Supplier {
private boolean initialized = false;
private volatile Supplier instanceSupplier;
public static Singleton from(final Supplier original) {
return new Singleton<>(original);
}
public static Singleton from(final Function original, T arg0) {
return fromLazy(original, () -> arg0);
}
public static Singleton from(final BiFunction original, T arg0, U arg1) {
return fromLazy(original, () -> arg0, () -> arg1);
}
public static Singleton fromLazy(final Function original, Supplier arg0Supplier) {
return from(() -> original.apply(arg0Supplier.get()));
}
public static Singleton fromLazy(final BiFunction original, Supplier arg0Supplier, Supplier arg1Supplier) {
return from(() -> original.apply(arg0Supplier.get(), arg1Supplier.get()));
}
public Singleton(final Supplier original) {
instanceSupplier = () -> {
synchronized (original) {
if (!initialized) {
final R singletonInstance = original.get();
instanceSupplier = () -> singletonInstance;
initialized = true;
}
return instanceSupplier.get();
}
};
}
@Override
public R get() {
return instanceSupplier.get();
}
}