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

com.arm.mbed.cloud.sdk.common.SynchronousMethod Maven / Gradle / Ivy

package com.arm.mbed.cloud.sdk.common;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;

import com.arm.mbed.cloud.sdk.annotations.Internal;
import com.arm.mbed.cloud.sdk.annotations.Nullable;
import com.arm.mbed.cloud.sdk.annotations.Preamble;

@Preamble(description = "Object to wait for an asynchronous method to complete")
@Internal
public class SynchronousMethod {

    private SynchronousMethod() {
        super();
    }

    @Preamble(description = "Asynchronous method")
    public interface AsynchronousMethod {
        /**
         * Gets a future task.
         * 
         * @return future task.
         * @throws MbedCloudException
         *             if an error happens during submission.
         */
        Future submit() throws MbedCloudException;
    }

    /**
     * Waits for the completion of an asynchronous call method.
     * 
     * @see AsynchronousMethod
     * @param asyncMethod
     *            asynchronous method to call.
     * @param timeout
     *            timeout to set. If null, it will wait indefinitely.
     * @param 
     *            type of the result
     * @return call result
     * @throws MbedCloudException
     *             if an error occurred during the call or the wait.
     */
    public static  T waitForCompletion(AsynchronousMethod asyncMethod, @Nullable TimePeriod timeout)
            throws MbedCloudException {
        final Future future = asyncMethod.submit();
        if (future == null) {
            return null;
        }
        try {
            if (timeout == null) {
                return future.get();
            }
            return future.get(timeout.getDuration(), timeout.getUnit());
        } catch (InterruptedException | ExecutionException | TimeoutException exception) {
            throw new MbedCloudException(exception);
        }

    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy