Skip to content

Instantly share code, notes, and snippets.

@fabiolimace
Last active February 25, 2024 13:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fabiolimace/da4ab36792b67939591ed7910ac9a4fc to your computer and use it in GitHub Desktop.
Save fabiolimace/da4ab36792b67939591ed7910ac9a4fc to your computer and use it in GitHub Desktop.
Lazy loader class Java
private static class Lazy<T> {
private T object = null;
private Supplier<T> supplier;
private static final ReentrantLock lock = new ReentrantLock();
public Lazy(Supplier<T> supplier) {
this.supplier = supplier;
}
public T get() {
if (object != null) {
return object;
}
lock.lock();
try {
if (object == null) {
this.object = supplier.get();
}
return this.object;
} finally {
lock.unlock();
}
}
}
private static class Proxy extends UuidFactory {
private UuidFactory factory = null;
private Supplier<UuidFactory> supplier;
private static final ReentrantLock lock = new ReentrantLock();
public Proxy(Supplier<UuidFactory> supplier) {
this.supplier = supplier;
}
public Proxy(Suppliers supplier) {
this((Supplier<UuidFactory>) supplier.getValue());
}
private UuidFactory get() {
if (factory != null) {
return factory;
}
lock.lock();
try {
if (factory == null) {
this.factory = supplier.get();
}
return this.factory;
} finally {
lock.unlock();
}
}
@Override
public UUID create() {
return get().create();
}
@Override
public UUID create(Parameters parameters) {
return get().create(parameters);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment