com.github.azbh111.utils.java.lang.ThreadLocalLazyField Maven / Gradle / Ivy
package com.github.azbh111.utils.java.lang;
import java.util.function.Supplier;
/**
*
* @author pyz
* @date 2019/5/4 4:03 PM
*/
public class ThreadLocalLazyField {
private final ThreadLocal threadLocal = new ThreadLocal();
private final Supplier supplier;
private ThreadLocalLazyField(Supplier supplier) {
this.supplier = supplier;
}
public static ThreadLocalLazyField from(Supplier supplier) {
return new ThreadLocalLazyField<>(supplier);
}
public T get() {
T value = threadLocal.get();
if (value == null) {
value = supplier.get();
threadLocal.set(value);
}
return value;
}
public ThreadLocalLazyField set(T value) {
threadLocal.set(value);
return this;
}
}