All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.azbh111.utils.java.lang.LazyField Maven / Gradle / Ivy

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;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy