All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.zipwhip.concurrent.FutureUtil Maven / Gradle / Ivy

package com.zipwhip.concurrent;

import com.zipwhip.executors.NamedThreadFactory;

import java.util.concurrent.*;

/**
 * Created with IntelliJ IDEA.
 * User: Michael
 * Date: 8/16/12
 * Time: 12:38 PM
 *
 * Convenience methods for creating/working with futures.
 */
public class FutureUtil {

    private static final Executor EVENTS = Executors.newSingleThreadExecutor(new NamedThreadFactory("FutureUtil-events"));

    public static  Future execute(Executor executor, Callable callable) {
        if (executor == null){
            throw new IllegalArgumentException("The executor can't be null!");
        }

        FutureTask task = new FutureTask(callable);

        executor.execute(task);

        return task;
    }

    public static  ObservableFuture execute(Executor executor, final Object sender, final Callable callable) {
        if (executor == null){
            throw new IllegalArgumentException("The executor can't be null!");
        }

        final ObservableFuture future = new DefaultObservableFuture(sender);

        executor.execute(new Runnable() {
            @Override
            public void run() {
                T result;

                try {
                    result = callable.call();
                } catch (Exception e) {
                    future.setFailure(e);
                    return;
                }
                future.setSuccess(result);
            }
        });

        return future;
    }

    public static  ObservableFuture execute(Executor executor, final Object sender, final Future future) {
        return execute(executor, null, sender, future);
    }

    public static  ObservableFuture execute(Executor executor, Executor eventExecutor, final Object sender, final Future future) {

        if (executor == null){
            // TODO: Change this to SimpleExecutor.getInstance() when we update our local code.
            executor = EVENTS;
        }

        final ObservableFuture result = new DefaultObservableFuture(sender, eventExecutor);

        executor.execute(new Runnable() {
            @Override
            public void run() {
            try {
                result.setSuccess(future.get());
            } catch (Exception e) {
                result.setFailure(e);
            }
            }
        });

        return result;
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy