/** * Return a thread-safe version of a {@code BiFunction} 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 BiFunction#apply(Object, 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> Type of function's first argument * @param <U> Type of function's second argument * @param <R> Type of function's third argument * @param function Function to return a thread-safe version of. * @return A thread-safe function */ public static <T,U,R> BiFunction<T,U,R> synchronizedBiFunction(final BiFunction<T,U,R> function) { if (isImmutable(function) && !(function instanceof AutoCloseable)) return function; // Return a function that is synchronized on the passed in function reference. return new ThreadSafeBiFunction<T,U,R>(function); }
@Override public R apply(T t, U u) { final BiFunction<T,U,R> function = f(); synchronized (function) { return function.apply(t, u); } } }
/** * Return a thread-safe version of a {@code BiFunction} 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 BiFunction#apply(Object, 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> Type of function's first argument * @param <U> Type of function's second argument * @param <R> Type of function's third argument * @param function Function to return a thread-safe version of. * @return A thread-safe function */ public static <T,U,R> BiFunction<T,U,R> synchronizedBiFunction(final BiFunction<T,U,R> function) { if (isImmutable(function) && !(function instanceof AutoCloseable)) return function; // Return a function that is synchronized on the passed in function reference. return new ThreadSafeBiFunction<T,U,R>(function); }
@Override public R apply(T t, U u) { final BiFunction<T,U,R> function = f(); synchronized (function) { return function.apply(t, u); } } }