com.github.azbh111.utils.java.lang.LazyField Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of utils-java Show documentation
Show all versions of utils-java Show documentation
com.github.azbh111:utils-java
The newest version!
package com.github.azbh111.utils.java.lang;
import java.util.function.Supplier;
/**
* @author pyz
* @date 2019/5/4 4:03 PM
*/
public class LazyField {
private volatile T value;
private final Supplier supplier;
private final Object lock = new Object();
private LazyField(Supplier supplier) {
this.supplier = supplier;
}
public static LazyField from(Supplier supplier) {
return new LazyField<>(supplier);
}
public T get() {
if (value == null) {
synchronized (lock) {
if (value == null) {
value = supplier.get();
}
}
}
return value;
}
public LazyField set(T value) {
synchronized (lock) {
this.value = value;
}
return this;
}
}