001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.commons.function;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020
021import java.util.*;
022import java.util.concurrent.atomic.*;
023import java.util.function.*;
024
025/** Supplier factories: memoizing wrappers moved from the former {@code Utils}. */
026@SuppressWarnings({
027   "java:S1118", // Utility class with static methods only.
028   "java:S1192" // Duplicated literals (argument/property names) read more clearly inline than as constants
029})
030public class Suppliers {
031
032   /** Constructor — this class is meant to be subclassed. */
033   protected Suppliers() {}
034
035   /**
036    * Thread-safe memoizing supplier (computes once, caches).
037    *
038    * @param <T> The type of value supplied.
039    * @param supplier The underlying supplier to memoize.  Must not be <jk>null</jk>.
040    * @return A new memoizing supplier.
041    */
042   @SuppressWarnings({
043      "java:S2789" // AtomicReference uses null for "uninitialized"; intentional.
044   })
045   public static <T> NullableSupplier<T> memoize(Supplier<T> supplier) {
046      reqnn("supplier", supplier);
047      var cache = new AtomicReference<Optional<T>>();
048      return () -> {
049         var h = cache.get();
050         if (h == null) {
051            h = o(supplier.get());
052            if (! cache.compareAndSet(null, h)) h = cache.get();
053         }
054         return h.orElse(null);
055      };
056   }
057
058   /**
059    * Resettable memoizing supplier.
060    *
061    * @param <T> The type of value supplied.
062    * @param supplier The underlying supplier to memoize.  Must not be <jk>null</jk>.
063    * @return A new resettable memoizing supplier.
064    */
065   public static <T> Memoizer<T> memoizer(Supplier<T> supplier) {
066      reqnn("supplier", supplier);
067      return new Memoizer<>(supplier);
068   }
069}