/** * Return a thread-safe version of a {@code Supplier} function. * If the function is guaranteed to be immutable (stateless) * then the function is returned, as it is thread safe, * otherwise a wrapper is returned that grabs synchronization * on {@code function} when calling {@link Supplier#get()}. * <BR> * If {@code function} implements {@code AutoCloseable} then * the function is assumed to be stateful and a thread-safe * version is returned. * @param <T> tuple type * @param function Function to return a thread-safe version of. * @return A thread-safe function */ public static <T> Supplier<T> synchronizedSupplier(final Supplier<T> function) { if (isImmutable(function) && !(function instanceof AutoCloseable)) return function; // Return a function that is synchronized on the passed in function reference. return new ThreadSafeSupplier<T>(function); }
@Override public T get() { final Supplier<T> function = f(); synchronized (function) { return function.get(); } } }
/** * Return a thread-safe version of a {@code Supplier} function. * If the function is guaranteed to be immutable (stateless) * then the function is returned, as it is thread safe, * otherwise a wrapper is returned that grabs synchronization * on {@code function} when calling {@link Supplier#get()}. * <BR> * If {@code function} implements {@code AutoCloseable} then * the function is assumed to be stateful and a thread-safe * version is returned. * @param <T> tuple type * @param function Function to return a thread-safe version of. * @return A thread-safe function */ public static <T> Supplier<T> synchronizedSupplier(final Supplier<T> function) { if (isImmutable(function) && !(function instanceof AutoCloseable)) return function; // Return a function that is synchronized on the passed in function reference. return new ThreadSafeSupplier<T>(function); }
@Override public T get() { final Supplier<T> function = f(); synchronized (function) { return function.get(); } } }