Class CoroutineScope

  • All Implemented Interfaces:
    org.obrel.core.Relatable

    public class CoroutineScope
    extends CoroutineEnvironment
    A scope that manages one or more running coroutines. A new scope is created through the factory method launch(CoroutineContext, ScopeCode) It executes an instance of the functional interface CoroutineScope.ScopeCode and blocks the invoking thread until the code and all coroutines by it have finished execution (either successfully or with an exception).

    An alternative way to launch a scope is by using the method produce(CoroutineContext, Function, ScopeCode). It also executes the given code (which in turn may start coroutines) but returns immediately after the code finished with a CoroutineScope.ScopeFuture instance. This sub-interface of Future can then be used to wait for the started coroutines to finish or to cancel the execution. As the name indicates, this method is mainly intended for scope executions that produce result. But it can also be used to just wrap a scope execution to handle it as a future and then ignore the result.

    A scope will also automatically close all (AutoCloseable) resources that are stored in it with relations that have the annotation MetaTypes.MANAGED.

    • Method Summary

      All Methods Static Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      void await()
      Blocks until all coroutines in this scope have finished execution.
      boolean await​(long timeout, java.util.concurrent.TimeUnit unit)
      Blocks until all coroutines in this scope have finished execution or a timeout expires.
      void cancel()
      Cancels the execution of all coroutines that are currently running in this scope.
      CoroutineContext context()
      Returns the context in which coroutines of this scope are executed.
      <T> Channel<T> getChannel​(ChannelId<T> id)
      Checks this scope and the CoroutineContext for a channel with the given ID.
      long getCoroutineCount()
      Returns the number of currently running coroutines.
      boolean hasChannel​(ChannelId<?> id)
      Checks whether a channel with the given ID exists in this scope or in the CoroutineContext.
      boolean isCancelled()
      Checks whether this scope has been cancelled.
      boolean isCancelOnError()
      Checks whether the execution of the other coroutines in this scope is canceled if an exception occurs in a coroutine.
      boolean isFinished()
      Non-blockingly checks whether this scope has finished execution of all coroutines.
      static void launch​(CoroutineContext context, CoroutineScope.ScopeCode code)
      Launches a new scope for the execution of coroutine in a specific context.
      static void launch​(CoroutineScope.ScopeCode code)
      Launches a new scope for the execution of coroutine in the default context.
      static <T> CoroutineScope.ScopeFuture<T> produce​(CoroutineContext context, java.util.function.Function<? super CoroutineScope,​T> getResult, CoroutineScope.ScopeCode code)
      Launches a new scope that is expected to produce a result and returns a Future instance that can be used to query the result.
      static <T> CoroutineScope.ScopeFuture<T> produce​(java.util.function.Function<? super CoroutineScope,​T> getResult, CoroutineScope.ScopeCode code)
      Launches a new scope that is expected to produce a result in the default context.
      void removeChannel​(ChannelId<?> id)
      Removes a channel from this scope or from the CoroutineContext.
      void setCancelOnError​(boolean cancelOnError)
      Sets the behavior on coroutine errors in the scope.
      java.lang.String toString()
      • Methods inherited from class org.obrel.core.RelatedObject

        deleteRelation, get, getRelation, getRelations, notifyRelationListeners, readRelations, relationsEqual, relationsHashCode, relationsString, set, set, transform, writeRelations
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
      • Methods inherited from interface org.obrel.core.Relatable

        deleteRelation, deleteRelations, getAll, getOption, getRelationCount, getRelations, hasFlag, hasRelation, hasRelations, init, set, set, set, setOption, streamRelations
    • Method Detail

      • launch

        public static void launch​(CoroutineContext context,
                                  CoroutineScope.ScopeCode code)
        Launches a new scope for the execution of coroutine in a specific context. This method will block the invoking thread until all coroutines launched by the argument builder have terminated, either successfully, by cancelation, or with errors.

        If one or more of the coroutines or the scope code throw an exception this method will throw a CoroutineScopeException as soon as all other coroutines have terminated. By default an error causes all other coroutines to be cancelled but that can be changed with setCancelOnError(boolean). If any other coroutines fail after the first error their continuations will also be added to the exception.

        Parameters:
        context - The coroutine context for the scope
        code - The code to execute in the scope
        Throws:
        CoroutineScopeException - If one or more of the executed coroutines failed
      • produce

        public static <T> CoroutineScope.ScopeFuture<T> produce​(CoroutineContext context,
                                                                java.util.function.Function<? super CoroutineScope,​T> getResult,
                                                                CoroutineScope.ScopeCode code)
        Launches a new scope that is expected to produce a result and returns a Future instance that can be used to query the result. The result will be retrieved after the coroutine execution finished from the scope by applying the result function. If the future object is only needed to wrap a scope execution this function
        Parameters:
        context - The coroutine context for the scope
        getResult - A function that retrieves the result from the scope or NULL to always return NULL
        code - The producing code to execute in the scope
        Returns:
        A future that provides access to the result of the scope execution
      • await

        public void await()
        Blocks until all coroutines in this scope have finished execution. If no coroutines are running or all have finished execution already this method returns immediately.
      • await

        public boolean await​(long timeout,
                             java.util.concurrent.TimeUnit unit)
        Blocks until all coroutines in this scope have finished execution or a timeout expires. If the timeout is reached this method will return but the scope will continue to execute. If necessary it can be cancelled by calling cancel().
        Parameters:
        timeout - The maximum time to wait
        unit - The unit of the timeout
        Returns:
        TRUE if the scope has finished execution; FALSE if the timeout was reached
      • cancel

        public void cancel()
        Cancels the execution of all coroutines that are currently running in this scope.
      • context

        public CoroutineContext context()
        Returns the context in which coroutines of this scope are executed.
        Returns:
        The coroutine context
      • getCoroutineCount

        public long getCoroutineCount()
        Returns the number of currently running coroutines. This will only be a momentary value as the execution of the coroutines happens asynchronously and coroutines may finish while querying this count.
        Returns:
        The number of running coroutines
      • isCancelOnError

        public boolean isCancelOnError()
        Checks whether the execution of the other coroutines in this scope is canceled if an exception occurs in a coroutine. Can be changed with setCancelOnError(boolean).
        Returns:
        TRUE if all coroutines are cancelled if a coroutine fails
      • isCancelled

        public boolean isCancelled()
        Checks whether this scope has been cancelled.
        Returns:
        TRUE if cancelled
      • isFinished

        public boolean isFinished()
        Non-blockingly checks whether this scope has finished execution of all coroutines. Due to the asynchronous nature of coroutine executions this method will only return when preceded by a blocking call like await().
        Returns:
        TRUE if finished
      • setCancelOnError

        public void setCancelOnError​(boolean cancelOnError)
        Sets the behavior on coroutine errors in the scope. If set to TRUE (which is the default) any exception in a coroutine will cancel the execution of this scope. If FALSE all other coroutines are allowed to finish execution (or fail too) before the scope's execution is finished. In any case the scope will throw a CoroutineScopeException if one or more errors occurred.
        Parameters:
        cancelOnError - TRUE to cancel running coroutine if an error occurs; FALSE to let them finish
      • toString

        public java.lang.String toString()
        Overrides:
        toString in class org.obrel.core.RelatedObject