Created
October 7, 2019 08:12
-
-
Save jonas-grgt/9c5e68de0c5504ba4da4dc094f193db6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* A thread-safe lazy object reference that will only initialize its value when get() is called. | |
*/ | |
public abstract class Lazy<T> { | |
private volatile T object; | |
private volatile boolean initialized; | |
@JsonValue | |
public T get() { | |
T result = object; | |
if (!initialized) { | |
synchronized (this) { | |
result = object; | |
if (!initialized) { | |
object = result = initialize(); | |
initialized = true; | |
} | |
} | |
} | |
return result; | |
} | |
@JsonCreator | |
public static <T> Lazy<T> value(final T value) { | |
return new Lazy<T>() { | |
@Override | |
protected T initialize() { | |
return value; | |
} | |
}; | |
} | |
public static <T> Lazy<T> supplier(final Supplier<T> supplier) { | |
return new Lazy<T>() { | |
@Override | |
protected T initialize() { | |
return supplier.get(); | |
} | |
}; | |
} | |
protected abstract T initialize(); | |
public synchronized boolean isInitialized() { | |
return initialized; | |
} | |
public synchronized void reset() { | |
initialized = false; | |
} | |
@Override | |
public String toString() { | |
return String.valueOf(get()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment