Transform a callback into a concurrent Callable. - Java java.util.concurrent

Java examples for java.util.concurrent:Callable

Description

Transform a callback into a concurrent Callable.

Demo Code


import java.util.concurrent.Callable;

public class Main{
    /**//from w w  w . ja v a  2  s . c om
     * Transform a callback into a Callable. <code>Callable#call()</code> delegates
     * to <code>callback.op(param)</code> and return <code>result</code> as result.
     * @param <P>
     * @param <R>
     * @param callback
     * @param param parameter that will be passed to the callback when the <code>Callable#call()</code>
     *    will be called.
     * @param result result that will be returned by <code>Callable#call()</code>
     * @return
     */
    public static <P, R> Callable<R> toCallable(final C1<P> callback,
            final P param, final R result) {
        return toCallable(toFunction(callback, result), param);
    }
    /**
     * Create a <code>Callable</code> whose method <code>call()</code> delegates
     * to <code>callback.op(param)</code>
     * @param <P>
     * @param <R>
     * @param function function that will be invoked by the <code>Callable</code>
     *  with the parameter <code>param</code>
     * @param param parameter that will be passed to the callback when the <code>Callable#call()</code>
     *    will be called.
     * @return
     */
    public static <P, R> Callable<R> toCallable(final F1<P, R> function,
            final P param) {
        return new Callable<R>() {
            public R call() throws Exception {
                return function.op(param);
            }
        };
    }
    public static <P, R> F1<P, R> toFunction(final C1<P> callback,
            final R result) {
        return new F1<P, R>() {
            public R op(P value) {
                callback.op(value);
                return result;
            }
        };
    }
}

Related Tutorials