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

delight.async.jre.Async Maven / Gradle / Ivy

Go to download

Asynchronous utilities for Java and GWT applications. Includes a simple promise implementation for Java.

There is a newer version: 0.1.5
Show newest version
package delight.async.jre;

import delight.async.AsyncCommon;
import delight.async.Operation;
import delight.async.Value;
import delight.async.callbacks.ValueCallback;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 

* Asynchronous utilities which are only available in Oracle Java, OpenJDK and * Android (and not for JavaScript environments). * * @author Max Rohde * */ public class Async extends AsyncCommon { /** *

* Executes the specified {@link Operation} operation and blocks the calling * thread until the operation is completed. * * @param operation * The deferred operation to be executed. * @return The result of the deferred operation. */ public static final T waitFor(final int timeout, final Operation operation) { final CountDownLatch latch = new CountDownLatch(1); final Value result = new Value(null); final Value failure = new Value(null); operation.apply(new ValueCallback() { @Override public void onFailure(final Throwable t) { failure.set(t); latch.countDown(); } @Override public void onSuccess(final T value) { result.set(value); latch.countDown(); } }); try { latch.await(timeout, TimeUnit.MILLISECONDS); } catch (final InterruptedException e) { throw new RuntimeException(e); } if (latch.getCount() > 0) { throw new RuntimeException("Operation not completed in timeout: " + operation); } if (failure.get() != null) { throw new RuntimeException(failure.get()); // throw new // RuntimeException("Exception while performing operation.", // failure.get()); } return result.get(); } /** * Executes the specified {@link Operation} operation and blocks the calling * thread until the operation is completed. * * @param operation * The deferred operation to be executed. * @return The result of the deferred operation. */ public static final T waitFor(final Operation operation) { return waitFor(30000, operation); } public static > void parallel(final OP[] operationsRaw) { parallel(Arrays.asList(operationsRaw)); } public static > void parallel(final List operationsRaw) { waitFor(new Operation>() { @Override public void apply(final ValueCallback> callback) { AsyncCommon.parallel(operationsRaw, callback); } }); } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy