![JAR search and dependency download from the Maven repository](/logo.png)
io.ultreia.java4all.lang.SingletonSupplier Maven / Gradle / Ivy
package io.ultreia.java4all.lang;
/*-
* #%L
* Java Lang extends by Ultreia.io
* %%
* Copyright (C) 2017 Ultreia.io
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* .
* #L%
*/
import java.io.Closeable;
import java.io.IOException;
import java.util.Objects;
import java.util.function.Supplier;
/**
* Created by tchemit on 28/09/17.
*
* @author Tony Chemit - [email protected]
*/
public class SingletonSupplier implements Supplier, Closeable {
private final Supplier supplier;
private O cache;
public static SingletonSupplier of(Supplier supplier) {
return new SingletonSupplier<>(supplier);
}
private SingletonSupplier(Supplier supplier) {
Objects.requireNonNull(supplier);
this.supplier = supplier;
}
@Override
public O get() {
if (cache == null) {
cache = supplier.get();
}
return cache;
}
@Override
public void close() {
if (cache != null && cache instanceof Closeable) {
try {
((Closeable) cache).close();
} catch (IOException e) {
throw new RuntimeException("Could not close " + cache, e);
} finally {
cache = null;
}
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy