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

io.ultreia.java4all.util.SingletonSupplier Maven / Gradle / Ivy

There is a newer version: 1.2.1
Show newest version
package io.ultreia.java4all.util;

/*-
 * #%L
 * Java Util extends by Ultreia.io
 * %%
 * Copyright (C) 2018 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.util.Objects;
import java.util.Optional;
import java.util.function.Supplier;

/**
 * Get a {@link Supplier} with a cached value acting as a singleton.
 * 

* To remove cached value, use method {@link #clear()}. *

* Created by tchemit on 28/09/17. * * @author Tony Chemit - [email protected] */ public class SingletonSupplier implements Supplier { private Supplier supplier; private final boolean requireNonNull; private O cache; protected SingletonSupplier(Supplier supplier, boolean requireNonNull) { this.supplier = Objects.requireNonNull(supplier); this.requireNonNull = requireNonNull; } public static SingletonSupplier of(Supplier supplier) { return of(supplier, true); } public static SingletonSupplier of(Supplier supplier,boolean requireNonNull) { return new SingletonSupplier<>(supplier, requireNonNull); } @Override public O get() { return cache == null ? cache = load() : cache; } public void setSupplier(Supplier supplier) { this.supplier = Objects.requireNonNull(supplier); clear(); } public Optional clear() { Optional result = Optional.ofNullable(cache); cache = null; return result; } public boolean withValue() { return cache != null; } protected O load() { O cache = supplier.get(); if (requireNonNull) { Objects.requireNonNull(cache, "Value can't not be null if requiredNonNull flag is set on."); } return cache; } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy