/** * Return a thread-safe version of a {@code Consumer} 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 Consumer#accept(Object)}. * <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> Consumer<T> synchronizedConsumer(final Consumer<T> function) { if (isImmutable(function) && !(function instanceof AutoCloseable)) return function; // Return a function that is synchronized on the passed in function reference. return new ThreadSafeConsumer<T>(function); }
@Override public void accept(T value) { final Consumer<T> function = f(); synchronized (function) { function.accept(value); } } }
/** * Return a thread-safe version of a {@code Consumer} 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 Consumer#accept(Object)}. * <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> Consumer<T> synchronizedConsumer(final Consumer<T> function) { if (isImmutable(function) && !(function instanceof AutoCloseable)) return function; // Return a function that is synchronized on the passed in function reference. return new ThreadSafeConsumer<T>(function); }
@Override public void accept(T value) { final Consumer<T> function = f(); synchronized (function) { function.accept(value); } } }