Last active
January 24, 2025 12:49
-
-
Save mskoroglu/a246e4652c95865402baaa40d96b425d to your computer and use it in GitHub Desktop.
A Thread-Safe and Lightweight Lazy Initialization Class in Java
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
import java.util.Objects; | |
import java.util.function.Supplier; | |
public final class Lazy<T> implements Supplier<T> { | |
private final Supplier<T> initializer; | |
private volatile T value; | |
private volatile boolean initialized = false; | |
public Lazy(final Supplier<T> initializer) { | |
this.initializer = Objects.requireNonNull(initializer, "Initializer cannot be null"); | |
} | |
@Override | |
public T get() { | |
if (!initialized) { | |
synchronized (this) { | |
if (!initialized) { | |
value = initializer.get(); | |
initialized = true; | |
} | |
} | |
} | |
return value; | |
} | |
@Override | |
public String toString() { | |
return initialized ? String.valueOf(value) : "Lazy[not initialized]"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A Thread-Safe and Lightweight Lazy Initialization Class in Java
This
Lazy<T>
class provides a lightweight and thread-safe way to implement lazy initialization in Java. It uses aSupplier<T>
to delay the creation of an object until it is first accessed, ensuring efficient resource usage. The implementation is optimized for single and multi-threaded scenarios, following best practices for thread safety.Key Features:
volatile
flag ensures that initialization happens only once, even under concurrent access.Supplier<T>
allows you to define any custom logic for creating the value.Usage Examples:
1. Lazy Initialization for a Static Field
Output:
2. Lazy Initialization for a Non-Static Field
Output:
Why Use This Class?
Feel free to use, modify, or enhance this class for your projects. 😊