package org.xbib.logging.configuration;

import java.util.function.Supplier;

/**
 * A configuration resource
 */
class LazyConfigurationResource<T> implements ConfigurationResource<T> {
    private final Supplier<T> supplier;
    private volatile T instance;

    LazyConfigurationResource(final Supplier<T> supplier) {
        this.supplier = supplier;
    }

    @Override
    public T get() {
        if (instance == null) {
            synchronized (this) {
                if (instance == null) {
                    instance = supplier.get();
                }
            }
        }
        return instance;
    }

    @Override
    public void close() throws Exception {
        synchronized (this) {
            if (instance instanceof AutoCloseable) {
                ((AutoCloseable) instance).close();
            }
            instance = null;
        }
    }
}
