Last active
February 25, 2024 13:15
-
-
Save fabiolimace/da4ab36792b67939591ed7910ac9a4fc to your computer and use it in GitHub Desktop.
Lazy loader class Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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