Class FiberAsync<V,​E extends java.lang.Throwable>

  • Type Parameters:
    V - The value returned by the async request
    E - An exception class that could be thrown by the async request
    All Implemented Interfaces:
    java.io.Serializable
    Direct Known Subclasses:
    AsyncCompletionStage, AsyncListenableFuture

    public abstract class FiberAsync<V,​E extends java.lang.Throwable>
    extends java.lang.Object
    implements java.io.Serializable
    A general helper class that transforms asynchronous requests to synchronous (fiber-blocking) calls.

    Usage example

    Assume that operation Foo.asyncOp(FooCompletion callback) is an asynchronous operation, where Completion is defined as:
    
     interface FooCompletion {
         void success(String result);
         void failure(FooException exception);
     }
     
    We then define the following subclass:
    
     class FooAsync extends FiberAsync<String, FooException> implements FooCompletion {
         {@literal @}Override
         public void success(String result) {
             asyncCompleted(result);
         }
    
         {@literal @}Override
         public void failure(FooException exception) {
             asyncFailed(exception);
         }
     }
     
    Then, to turn the operation into a fiber-blocking one, we can define:
    
     String op() {
         return new FooAsync() {
             protected void requestAsync() {
                 Foo.asyncOp(this);
             }
         }.run();
     }
     
    See Also:
    Serialized Form
    • Constructor Summary

      Constructors 
      Constructor Description
      FiberAsync()
      Same as `FiberAsync(false)`
      FiberAsync​(boolean immediateExec)  
    • Method Summary

      All Methods Static Methods Instance Methods Abstract Methods Concrete Methods 
      Modifier and Type Method Description
      protected void asyncCompleted​(V result)
      This method must be called by the callback upon successful completion of the asynchronous operation.
      protected void asyncFailed​(java.lang.Throwable t)
      This method must be called by the callback upon a failure of the asynchronous operation.
      V getResult()
      Returns the result of the asynchronous operation if it has completed, or throws an exception if it completed unsuccessfully.
      protected void interrupted()
      Called when the fiber calling run() is interrupted during the call.
      boolean isCompleted()
      Tests whether or not the asynchronous operation represented by this `FiberAsyc` has completed.
      protected void prepark()
      Called by the fiber if this `FiberAsync` is in immediate-exec mode, immediately before attempting to block while running in the callback's thread.
      protected abstract void requestAsync()
      A user of this class must override this method to start the asynchronous operation and register the callback.
      protected V requestSync()
      Called if run() is not being executed in a fiber.
      protected V requestSync​(long timeout, java.util.concurrent.TimeUnit unit)
      Called if run(long, TimeUnit) is not being executed in a fiber.
      V run()
      Runs the asynchronous operation, blocks until it completes and returns its result.
      V run​(long timeout, java.util.concurrent.TimeUnit unit)
      Runs the asynchronous operation, blocks until it completes (but only up to the given timeout duration) and returns its result.
      V run​(Timeout timeout)
      Runs the asynchronous operation, blocks until it completes (but only up to the given timeout duration) and returns its result.
      static <V,​E extends java.lang.Exception>
      V
      runBlocking​(java.util.concurrent.ExecutorService exec, long timeout, java.util.concurrent.TimeUnit unit, co.paralleluniverse.common.util.CheckedCallable<V,​E> callable)
      Runs a thread-blocking operation on a given thread pool, blocks (the fiber) until the operation completes (but no longer than the specified timeout) and returns its result.
      static <V,​E extends java.lang.Exception>
      V
      runBlocking​(java.util.concurrent.ExecutorService exec, co.paralleluniverse.common.util.CheckedCallable<V,​E> callable)
      Runs a thread-blocking operation on a given thread pool, blocks (the fiber) until the operation completes and returns its result.
      static <V,​E extends java.lang.Exception>
      V
      runBlocking​(java.util.concurrent.ExecutorService exec, Timeout timeout, co.paralleluniverse.common.util.CheckedCallable<V,​E> callable)
      Runs a thread-blocking operation on a given thread pool, blocks (the fiber) until the operation completes (but no longer than the specified timeout) and returns its result.
      protected void waitForRegistration()
      Spins until requestAsync returns.
      protected E wrapException​(java.lang.Throwable t)
      Takes the exception generated by the async operation and possibly wraps it in an exception that will be thrown by the run method.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Constructor Detail

      • FiberAsync

        public FiberAsync()
        Same as `FiberAsync(false)`
      • FiberAsync

        public FiberAsync​(boolean immediateExec)
        Parameters:
        immediateExec - Whether the fiber should be executed in the same thread as the callback. Should generally be set to `false`.
    • Method Detail

      • run

        public V run()
              throws E extends java.lang.Throwable,
                     SuspendExecution,
                     java.lang.InterruptedException
        Runs the asynchronous operation, blocks until it completes and returns its result. Throws an exception if the operation has failed.

        In immediate exec mode, when this method returns we are running within the handler, and will need to call Fiber.yield() to return from the handler.

        Returns:
        the result of the async operation as set in the call to asyncCompleted.
        Throws:
        E - if the async computation failed and an exception was set in a call to asyncFailed.
        java.lang.InterruptedException
        E extends java.lang.Throwable
        SuspendExecution
      • run

        public V run​(long timeout,
                     java.util.concurrent.TimeUnit unit)
              throws E extends java.lang.Throwable,
                     SuspendExecution,
                     java.lang.InterruptedException,
                     java.util.concurrent.TimeoutException
        Runs the asynchronous operation, blocks until it completes (but only up to the given timeout duration) and returns its result. Throws an exception if the operation has failed.

        In immediate exec mode, when this method returns we are running within the handler, and will need to call Fiber.yield() to return from the handler.

        Parameters:
        timeout - the maximum duration to wait for the result
        unit - timeout's time unit
        Returns:
        the result of the async operation as set in the call to asyncCompleted.
        Throws:
        E - if the async computation failed and an exception was set in a call to asyncFailed.
        java.util.concurrent.TimeoutException - if the operation had not completed by the time the timeout has elapsed.
        java.lang.InterruptedException
        E extends java.lang.Throwable
        SuspendExecution
      • run

        public V run​(Timeout timeout)
              throws E extends java.lang.Throwable,
                     SuspendExecution,
                     java.lang.InterruptedException,
                     java.util.concurrent.TimeoutException
        Runs the asynchronous operation, blocks until it completes (but only up to the given timeout duration) and returns its result. Throws an exception if the operation has failed.

        In immediate exec mode, when this method returns we are running within the handler, and will need to call Fiber.yield() to return from the handler.

        Parameters:
        timeout - the method will not block for longer than the amount remaining in the Timeout
        Returns:
        the result of the async operation as set in the call to asyncCompleted.
        Throws:
        E - if the async computation failed and an exception was set in a call to asyncFailed.
        java.util.concurrent.TimeoutException - if the operation had not completed by the time the timeout has elapsed.
        java.lang.InterruptedException
        E extends java.lang.Throwable
        SuspendExecution
      • waitForRegistration

        protected final void waitForRegistration()
        Spins until requestAsync returns. Can be called from overrides of run (and must be called by the fiber that's calling run).
      • interrupted

        protected void interrupted()
        Called when the fiber calling run() is interrupted during the call.
      • requestAsync

        protected abstract void requestAsync()
        A user of this class must override this method to start the asynchronous operation and register the callback. This method may not use any ThreadLocals.
      • requestSync

        protected V requestSync()
                         throws E extends java.lang.Throwable,
                                java.lang.InterruptedException,
                                java.util.concurrent.ExecutionException
        Called if run() is not being executed in a fiber. Should perform the operation synchronously and return its result. The default implementation of this method throws an `IllegalThreadStateException`.
        Returns:
        The operation's result.
        Throws:
        E
        java.lang.InterruptedException
        E extends java.lang.Throwable
        java.util.concurrent.ExecutionException
      • requestSync

        protected V requestSync​(long timeout,
                                java.util.concurrent.TimeUnit unit)
                         throws java.lang.InterruptedException,
                                java.util.concurrent.ExecutionException,
                                java.util.concurrent.TimeoutException,
                                E extends java.lang.Throwable
        Called if run(long, TimeUnit) is not being executed in a fiber. Should perform the operation synchronously and return its result. The default implementation of this method throws an `IllegalThreadStateException`.
        Parameters:
        timeout - the maximum duration to wait for the result
        unit - timeout's time unit
        Returns:
        The operation's result.
        Throws:
        E
        java.lang.InterruptedException
        java.util.concurrent.ExecutionException
        java.util.concurrent.TimeoutException
        E extends java.lang.Throwable
      • asyncCompleted

        protected void asyncCompleted​(V result)
        This method must be called by the callback upon successful completion of the asynchronous operation.
        Parameters:
        result - The operation's result
      • asyncFailed

        protected void asyncFailed​(java.lang.Throwable t)
        This method must be called by the callback upon a failure of the asynchronous operation.
        Parameters:
        t - The exception that caused the failure, or an exception to be associated with it. Must not be `null`.
      • prepark

        protected void prepark()
        Called by the fiber if this `FiberAsync` is in immediate-exec mode, immediately before attempting to block while running in the callback's thread. Can be overridden by subclasses running in immediate-exec mode to verify whether a park is allowed.
      • isCompleted

        public final boolean isCompleted()
        Tests whether or not the asynchronous operation represented by this `FiberAsyc` has completed.
      • getResult

        public final V getResult()
                          throws E extends java.lang.Throwable
        Returns the result of the asynchronous operation if it has completed, or throws an exception if it completed unsuccessfully. If the operation has not yet completed, this method throws an `IllegalStateException`.
        Returns:
        the result of the asynchronous operation if it has completed.
        Throws:
        E - if the async computation failed and an exception was set in a call to asyncFailed.
        java.lang.IllegalStateException - if the operation has not yet completed.
        E extends java.lang.Throwable
      • wrapException

        protected E wrapException​(java.lang.Throwable t)
        Takes the exception generated by the async operation and possibly wraps it in an exception that will be thrown by the run method.
      • runBlocking

        public static <V,​E extends java.lang.Exception> V runBlocking​(java.util.concurrent.ExecutorService exec,
                                                                            co.paralleluniverse.common.util.CheckedCallable<V,​E> callable)
                                                                     throws E extends java.lang.Exception,
                                                                            SuspendExecution,
                                                                            java.lang.InterruptedException
        Runs a thread-blocking operation on a given thread pool, blocks (the fiber) until the operation completes and returns its result. This method is useful to transform thread-blocking calls that don't have corresponding asynchronous operations into a fiber-blocking operation.
        Parameters:
        exec - the thread-pool on which the thread-blocking operation will be run
        callable - the operation
        Returns:
        the result of the operation
        Throws:
        E - if the operation has thrown an exception
        E extends java.lang.Exception
        SuspendExecution
        java.lang.InterruptedException
      • runBlocking

        public static <V,​E extends java.lang.Exception> V runBlocking​(java.util.concurrent.ExecutorService exec,
                                                                            long timeout,
                                                                            java.util.concurrent.TimeUnit unit,
                                                                            co.paralleluniverse.common.util.CheckedCallable<V,​E> callable)
                                                                     throws E extends java.lang.Exception,
                                                                            SuspendExecution,
                                                                            java.lang.InterruptedException,
                                                                            java.util.concurrent.TimeoutException
        Runs a thread-blocking operation on a given thread pool, blocks (the fiber) until the operation completes (but no longer than the specified timeout) and returns its result. This method is useful to transform thread-blocking calls that don't have corresponding asynchronous operations into a fiber-blocking operation.
        Parameters:
        exec - the thread-pool on which the thread-blocking operation will be run
        timeout - the maximum duration to wait for the operation to complete
        unit - timeout's time unit.
        callable - the operation
        Returns:
        the result of the operation
        Throws:
        E - if the operation has thrown an exception
        java.util.concurrent.TimeoutException - if the timeout expires before the operation completes.
        E extends java.lang.Exception
        SuspendExecution
        java.lang.InterruptedException
      • runBlocking

        public static <V,​E extends java.lang.Exception> V runBlocking​(java.util.concurrent.ExecutorService exec,
                                                                            Timeout timeout,
                                                                            co.paralleluniverse.common.util.CheckedCallable<V,​E> callable)
                                                                     throws E extends java.lang.Exception,
                                                                            SuspendExecution,
                                                                            java.lang.InterruptedException,
                                                                            java.util.concurrent.TimeoutException
        Runs a thread-blocking operation on a given thread pool, blocks (the fiber) until the operation completes (but no longer than the specified timeout) and returns its result. This method is useful to transform thread-blocking calls that don't have corresponding asynchronous operations into a fiber-blocking operation.
        Parameters:
        exec - the thread-pool on which the thread-blocking operation will be run
        timeout - the maximum duration to wait for the operation to complete
        callable - the operation
        Returns:
        the result of the operation
        Throws:
        E - if the operation has thrown an exception
        java.util.concurrent.TimeoutException - if the timeout expires before the operation completes.
        E extends java.lang.Exception
        SuspendExecution
        java.lang.InterruptedException