Class TaskService

  • All Implemented Interfaces:
    java.util.concurrent.Executor, java.util.concurrent.ExecutorService, java.util.concurrent.ScheduledExecutorService

    public class TaskService
    extends Service
    implements java.util.concurrent.ScheduledExecutorService
    Application service capable of running and scheduling tasks asynchronously. The service instance returned will not invoke the runnable task in the current thread.

    In addition to allowing pooling, this method will ensure that the threads executing the tasks will have the thread local variables copied from the calling thread. This will ensure that call to static methods like Application.getCurrent() still work.

    Also, note that this executor service will be shared among all Restlets and Resources that are part of your context. In general this context corresponds to a parent Application's context. If you want to have your own service instance, you can use the wrap(ScheduledExecutorService) method to ensure that thread local variables are correctly set.
    Author:
    Jerome Louvel, Doug Lea (docs of ExecutorService in public domain), Tim Peierls
    • Constructor Summary

      Constructors 
      Constructor Description
      TaskService()
      Constructor.
      TaskService​(boolean enabled)
      Constructor.
      TaskService​(boolean enabled, boolean daemon)
      Constructor.
      TaskService​(boolean enabled, int corePoolSize)
      Constructor.
      TaskService​(int corePoolSize)
      Constructor.
    • Method Summary

      All Methods Static Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      boolean awaitTermination​(long timeout, java.util.concurrent.TimeUnit unit)
      Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.
      protected java.util.concurrent.ScheduledExecutorService createExecutorService​(int corePoolSize)
      Creates a new JDK executor service that will be wrapped.
      protected java.util.concurrent.ThreadFactory createThreadFactory()
      Creates a new thread factory that will properly name the Restlet created threads with a "restlet-" prefix.
      void execute​(java.lang.Runnable command)
      Executes the given command asynchronously.
      int getCorePoolSize()
      Returns the core pool size defining the maximum number of threads.
      java.util.List invokeAll​(java.util.Collection tasks)
      Executes the given tasks, returning a list of Futures holding their status and results when all complete.

      Due to a breaking change between Java SE versions 5 and 6, and in order to maintain compatibility both at the source and binary level, we have removed the generic information from this method.
      java.util.List invokeAll​(java.util.Collection tasks, long timeout, java.util.concurrent.TimeUnit unit)
      Executes the given tasks, returning a list of Futures holding their status and results when all complete or the timeout expires, whichever happens first.
      java.lang.Object invokeAny​(java.util.Collection tasks)
      Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do.
      java.lang.Object invokeAny​(java.util.Collection tasks, long timeout, java.util.concurrent.TimeUnit unit)
      Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do before the given timeout elapses.
      boolean isDaemon()
      Indicates whether the threads are created as daemon threads.
      boolean isShutdown()
      Returns true if this executor has been shut down.
      boolean isShutdownAllowed()
      Indicates if the shutdown() and shutdownNow() methods are allowed to effectively shutdown the wrapped executor service.
      boolean isTerminated()
      Returns true if all tasks have completed following shut down.
      java.util.concurrent.ScheduledFuture<?> schedule​(java.lang.Runnable command, long delay, java.util.concurrent.TimeUnit unit)
      Creates and executes a one-shot action that becomes enabled after the given delay.
      <V> java.util.concurrent.ScheduledFuture<V> schedule​(java.util.concurrent.Callable<V> callable, long delay, java.util.concurrent.TimeUnit unit)
      Creates and executes a ScheduledFuture that becomes enabled after the given delay.
      java.util.concurrent.ScheduledFuture<?> scheduleAtFixedRate​(java.lang.Runnable command, long initialDelay, long period, java.util.concurrent.TimeUnit unit)
      Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is executions will commence after initialDelay then initialDelay+period, then initialDelay + 2 * period, and so on.
      java.util.concurrent.ScheduledFuture<?> scheduleWithFixedDelay​(java.lang.Runnable command, long initialDelay, long delay, java.util.concurrent.TimeUnit unit)
      Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next.
      void setCorePoolSize​(int corePoolSize)
      Sets the core pool size defining the maximum number of threads.
      void setDaemon​(boolean daemon)
      Indicates whether or not the threads are daemon threads.
      void setShutdownAllowed​(boolean allowShutdown)
      Indicates if the shutdown() and shutdownNow() methods are allowed to effectively shutdown the wrapped executor service.
      void shutdown()
      Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.
      java.util.List<java.lang.Runnable> shutdownNow()
      Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.
      void start()
      Starts the Restlet.
      void stop()
      Stops the Restlet.
      java.util.concurrent.Future<?> submit​(java.lang.Runnable task)  
      <T> java.util.concurrent.Future<T> submit​(java.lang.Runnable task, T result)  
      <T> java.util.concurrent.Future<T> submit​(java.util.concurrent.Callable<T> task)
      Submits a value-returning task for execution and returns a Future representing the pending results of the task.
      static java.util.concurrent.ScheduledExecutorService wrap​(java.util.concurrent.ScheduledExecutorService executorService)
      Wraps a JDK executor service to ensure that the threads executing the tasks will have the thread local variables copied from the calling thread.
      • Methods inherited from class java.lang.Object

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

      • TaskService

        public TaskService()
        Constructor. Enables the service and set the core pool size to 4 by default.
      • TaskService

        public TaskService​(boolean enabled)
        Constructor. Set the core pool size to 4 by default.
        Parameters:
        enabled - True if the service has been enabled.
      • TaskService

        public TaskService​(boolean enabled,
                           boolean daemon)
        Constructor. Set the core pool size to 4 by default.
        Parameters:
        enabled - True if the service has been enabled.
        daemon - True if the threads are created as daemon threads.
      • TaskService

        public TaskService​(boolean enabled,
                           int corePoolSize)
        Constructor. The default minimum size
        Parameters:
        enabled - True if the service has been enabled.
        corePoolSize - The core pool size defining the maximum number of threads.
      • TaskService

        public TaskService​(int corePoolSize)
        Constructor.
        Parameters:
        corePoolSize - The core pool size defining the maximum number of threads.
    • Method Detail

      • wrap

        public static java.util.concurrent.ScheduledExecutorService wrap​(java.util.concurrent.ScheduledExecutorService executorService)
        Wraps a JDK executor service to ensure that the threads executing the tasks will have the thread local variables copied from the calling thread. This will ensure that call to static methods like Application.getCurrent() still work.
        Parameters:
        executorService - The JDK service to wrap.
        Returns:
        The wrapper service to use.
      • awaitTermination

        public boolean awaitTermination​(long timeout,
                                        java.util.concurrent.TimeUnit unit)
                                 throws java.lang.InterruptedException
        Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.
        Specified by:
        awaitTermination in interface java.util.concurrent.ExecutorService
        Parameters:
        timeout - The maximum time to wait.
        unit - The time unit.
        Returns:
        True if this executor terminated and false if the timeout elapsed before termination.
        Throws:
        java.lang.InterruptedException
      • createExecutorService

        protected java.util.concurrent.ScheduledExecutorService createExecutorService​(int corePoolSize)
        Creates a new JDK executor service that will be wrapped. By default it calls Executors.newCachedThreadPool(ThreadFactory), passing the result of createThreadFactory() as a parameter.
        Parameters:
        corePoolSize - The core pool size defining the maximum number of threads.
        Returns:
        A new JDK executor service.
      • createThreadFactory

        protected java.util.concurrent.ThreadFactory createThreadFactory()
        Creates a new thread factory that will properly name the Restlet created threads with a "restlet-" prefix.
        Returns:
        A new thread factory.
      • execute

        public void execute​(java.lang.Runnable command)
        Executes the given command asynchronously.
        Specified by:
        execute in interface java.util.concurrent.Executor
        Parameters:
        command - The command to execute.
      • getCorePoolSize

        public int getCorePoolSize()
        Returns the core pool size defining the maximum number of threads.
        Returns:
        The core pool size defining the maximum number of threads.
      • invokeAll

        public java.util.List invokeAll​(java.util.Collection tasks)
                                 throws java.lang.InterruptedException
        Executes the given tasks, returning a list of Futures holding their status and results when all complete.

        Due to a breaking change between Java SE versions 5 and 6, and in order to maintain compatibility both at the source and binary level, we have removed the generic information from this method. You can check the ExecutorService interface for typing details.
        Specified by:
        invokeAll in interface java.util.concurrent.ExecutorService
        Parameters:
        tasks - The task to execute.
        Returns:
        The list of futures.
        Throws:
        java.lang.InterruptedException
      • invokeAll

        public java.util.List invokeAll​(java.util.Collection tasks,
                                        long timeout,
                                        java.util.concurrent.TimeUnit unit)
                                 throws java.lang.InterruptedException
        Executes the given tasks, returning a list of Futures holding their status and results when all complete or the timeout expires, whichever happens first. Future.isDone() is true for each element of the returned list. Upon return, tasks that have not completed are canceled. Note that a completed task could have terminated either normally or by throwing an exception. The results of this method are undefined if the given collection is modified while this operation is in progress.

        Due to a breaking change between Java SE versions 5 and 6, and in order to maintain compatibility both at the source and binary level, we have removed the generic information from this method. You can check the ExecutorService interface for typing details.
        Specified by:
        invokeAll in interface java.util.concurrent.ExecutorService
        Parameters:
        tasks - The task to execute.
        timeout - The maximum time to wait.
        unit - The time unit.
        Returns:
        The list of futures.
        Throws:
        java.lang.InterruptedException
      • invokeAny

        public java.lang.Object invokeAny​(java.util.Collection tasks)
                                   throws java.lang.InterruptedException,
                                          java.util.concurrent.ExecutionException
        Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do. Upon normal or exceptional return, tasks that have not completed are cancelled. The results of this method are undefined if the given collection is modified while this operation is in progress. Due to a breaking change between Java SE versions 5 and 6, and in order to maintain compatibility both at the source and binary level, we have removed the generic information from this method. You can check the ExecutorService interface for typing details.
        Specified by:
        invokeAny in interface java.util.concurrent.ExecutorService
        Parameters:
        tasks - The task to execute.
        Returns:
        The result returned by one of the tasks.
        Throws:
        java.lang.InterruptedException
        java.util.concurrent.ExecutionException
      • invokeAny

        public java.lang.Object invokeAny​(java.util.Collection tasks,
                                          long timeout,
                                          java.util.concurrent.TimeUnit unit)
                                   throws java.lang.InterruptedException,
                                          java.util.concurrent.ExecutionException,
                                          java.util.concurrent.TimeoutException
        Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do before the given timeout elapses. Upon normal or exceptional return, tasks that have not completed are cancelled. The results of this method are undefined if the given collection is modified while this operation is in progress. Due to a breaking change between Java SE versions 5 and 6, and in order to maintain compatibility both at the source and binary level, we have removed the generic information from this method. You can check the ExecutorService interface for typing details.
        Specified by:
        invokeAny in interface java.util.concurrent.ExecutorService
        Parameters:
        tasks - The task to execute.
        timeout - The maximum time to wait.
        unit - The time unit.
        Returns:
        The result returned by one of the tasks.
        Throws:
        java.lang.InterruptedException
        java.util.concurrent.ExecutionException
        java.util.concurrent.TimeoutException
      • isDaemon

        public boolean isDaemon()
        Indicates whether the threads are created as daemon threads.
        Returns:
        True if the threads are created as daemon threads.
      • isShutdown

        public boolean isShutdown()
        Returns true if this executor has been shut down.
        Specified by:
        isShutdown in interface java.util.concurrent.ExecutorService
        Returns:
        True if this executor has been shut down.
      • isShutdownAllowed

        public boolean isShutdownAllowed()
        Indicates if the shutdown() and shutdownNow() methods are allowed to effectively shutdown the wrapped executor service. Return false by default.
        Returns:
        True if shutdown is allowed.
      • isTerminated

        public boolean isTerminated()
        Returns true if all tasks have completed following shut down. Note that isTerminated is never true unless either shutdown or shutdownNow was called first.
        Specified by:
        isTerminated in interface java.util.concurrent.ExecutorService
        Returns:
        True if all tasks have completed following shut down.
      • schedule

        public <V> java.util.concurrent.ScheduledFuture<V> schedule​(java.util.concurrent.Callable<V> callable,
                                                                    long delay,
                                                                    java.util.concurrent.TimeUnit unit)
        Creates and executes a ScheduledFuture that becomes enabled after the given delay.
        Specified by:
        schedule in interface java.util.concurrent.ScheduledExecutorService
        Parameters:
        callable - The function to execute.
        delay - The time from now to delay execution.
        unit - The time unit of the delay parameter.
        Returns:
        a ScheduledFuture that can be used to extract result or cancel.
        Throws:
        java.util.concurrent.RejectedExecutionException - if task cannot be scheduled for execution.
        java.lang.NullPointerException - if callable is null
      • schedule

        public java.util.concurrent.ScheduledFuture<?> schedule​(java.lang.Runnable command,
                                                                long delay,
                                                                java.util.concurrent.TimeUnit unit)
        Creates and executes a one-shot action that becomes enabled after the given delay.
        Specified by:
        schedule in interface java.util.concurrent.ScheduledExecutorService
        Parameters:
        command - The task to execute.
        delay - The time from now to delay execution.
        unit - The time unit of the delay parameter.
        Returns:
        a Future representing pending completion of the task, and whose get() method will return null upon completion.
        Throws:
        java.util.concurrent.RejectedExecutionException - if task cannot be scheduled for execution.
        java.lang.NullPointerException - if command is null
      • scheduleAtFixedRate

        public java.util.concurrent.ScheduledFuture<?> scheduleAtFixedRate​(java.lang.Runnable command,
                                                                           long initialDelay,
                                                                           long period,
                                                                           java.util.concurrent.TimeUnit unit)
        Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is executions will commence after initialDelay then initialDelay+period, then initialDelay + 2 * period, and so on. If any execution of the task encounters an exception, subsequent executions are suppressed. Otherwise, the task will only terminate via cancellation or termination of the executor.
        Specified by:
        scheduleAtFixedRate in interface java.util.concurrent.ScheduledExecutorService
        Parameters:
        command - The task to execute.
        initialDelay - The time to delay first execution.
        period - The period between successive executions.
        unit - The time unit of the initialDelay and period parameters
        Returns:
        a Future representing pending completion of the task, and whose get() method will throw an exception upon cancellation.
        Throws:
        java.util.concurrent.RejectedExecutionException - if task cannot be scheduled for execution.
        java.lang.NullPointerException - if command is null
        java.lang.IllegalArgumentException - if period less than or equal to zero.
      • scheduleWithFixedDelay

        public java.util.concurrent.ScheduledFuture<?> scheduleWithFixedDelay​(java.lang.Runnable command,
                                                                              long initialDelay,
                                                                              long delay,
                                                                              java.util.concurrent.TimeUnit unit)
        Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next. If any execution of the task encounters an exception, subsequent executions are suppressed. Otherwise, the task will only terminate via cancellation or termination of the executor.
        Specified by:
        scheduleWithFixedDelay in interface java.util.concurrent.ScheduledExecutorService
        Parameters:
        command - The task to execute.
        initialDelay - The time to delay first execution.
        delay - The delay between the termination of one execution and the commencement of the next.
        unit - The time unit of the initialDelay and delay parameters
        Returns:
        a Future representing pending completion of the task, and whose get() method will throw an exception upon cancellation.
        Throws:
        java.util.concurrent.RejectedExecutionException - if task cannot be scheduled for execution.
        java.lang.NullPointerException - if command is null
        java.lang.IllegalArgumentException - if delay less than or equal to zero.
      • setCorePoolSize

        public void setCorePoolSize​(int corePoolSize)
        Sets the core pool size defining the maximum number of threads.
        Parameters:
        corePoolSize - The core pool size defining the maximum number of threads.
      • setDaemon

        public void setDaemon​(boolean daemon)
        Indicates whether or not the threads are daemon threads. True by default.
        Parameters:
        daemon - True if the threads are daemon threads.
      • setShutdownAllowed

        public void setShutdownAllowed​(boolean allowShutdown)
        Indicates if the shutdown() and shutdownNow() methods are allowed to effectively shutdown the wrapped executor service.
        Parameters:
        allowShutdown - True if shutdown is allowed.
      • shutdown

        public void shutdown()
        Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.
        Specified by:
        shutdown in interface java.util.concurrent.ExecutorService
      • shutdownNow

        public java.util.List<java.lang.Runnable> shutdownNow()
        Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.
        Specified by:
        shutdownNow in interface java.util.concurrent.ExecutorService
        Returns:
        The list of tasks that never commenced execution;
      • start

        public void start()
                   throws java.lang.Exception
        Description copied from class: Service
        Starts the Restlet.
        Overrides:
        start in class Service
        Throws:
        java.lang.Exception
      • stop

        public void stop()
                  throws java.lang.Exception
        Description copied from class: Service
        Stops the Restlet.
        Overrides:
        stop in class Service
        Throws:
        java.lang.Exception
      • submit

        public <T> java.util.concurrent.Future<T> submit​(java.util.concurrent.Callable<T> task)
        Submits a value-returning task for execution and returns a Future representing the pending results of the task.
        Specified by:
        submit in interface java.util.concurrent.ExecutorService
        Parameters:
        task - The task to submit.
        Returns:
        A Future representing pending completion of the task, and whose get() method will return the given result upon completion.
      • submit

        public java.util.concurrent.Future<?> submit​(java.lang.Runnable task)
        Specified by:
        submit in interface java.util.concurrent.ExecutorService
        Parameters:
        task - The task to submit.
        Returns:
        A Future representing pending completion of the task, and whose get() method will return the given result upon completion.
      • submit

        public <T> java.util.concurrent.Future<T> submit​(java.lang.Runnable task,
                                                         T result)
        Specified by:
        submit in interface java.util.concurrent.ExecutorService
        Parameters:
        task - The task to submit.
        result - The result to return.
        Returns:
        A Future representing pending completion of the task, and whose get() method will return the given result upon completion.