org.openide.util 8.19.1

org.openide.util
Class RequestProcessor

java.lang.Object
  extended by org.openide.util.RequestProcessor
All Implemented Interfaces:
Executor, ExecutorService, ScheduledExecutorService

public final class RequestProcessor
extends Object
implements ScheduledExecutorService

Request processor is Executor (since version 7.16) capable to perform asynchronous requests in a dedicated thread pool. There are several use cases for RequestProcessor, most of them start with creating own RequestProcessor instance (which by itself is quite lightweight).

Do something later
In case you want something to be done later in some background thread, create an instance of RequestProcessor and post tasks to it.
 private static final RequestProcessor RP = new RequestProcessor(MyClass.class);
 // later
 RP.post(runnable, delay)
 
The above example guarantees that there is at most one runnable being processed in parallel. All your requests are serialized and processed one by one. RP works here like a simple mutex.

In case you want more tasks to run in parallel (not very often use case) you can specify higher throughput via RequestProcessor(java.lang.String, int). Then the RP works like a queue of requests passing through a semaphore with predefined number of DOWN()s.

You can wait for your tasks to be processed by keeping a reference to the last one and using waitFinished():

 private static final RequestProcessor RP = new RequestProcessor("My tasks");
 private volatile RequestProcessor.Task last;

 // when posting update the task
 last = RP.post(runnable, delay)

 // later wait
 last.waitFinished()
 
Periodic task
It is also possible to do something periodically. Use the schedule method:
 class Periodic implements Runnable {
   private static final RequestProcessor RP = new RequestProcessor(Periodic.class);
   private final RequestProcessor.Task CLEANER = RP.create(this);
   public void run() {
     doTheWork();
     CLEANER.schedule(DELAY);
   }
 }
 
Please think twice before using such periodic background activity. It is generally considered evil if some code runs without any user action. Your code shall respect the application's state, and for example when the application is minimized, do nothing.
Sliding task
Often you want to perform an update of your object internals based on changes in some model. However your update may be costly and you want to do it just once, regardless of how many changes are reported by the model. This can be achieved with a sliding task:
 class Updater implements PropertyChangeListener, Runnable {
   private static final RequestProcessor RP = new RequestProcessor(Updater.class);
   private final RequestProcessor.Task UPDATE = RP.create(this);

   public void propertyChange(PropertyChangeEvent ev) {
     UPDATE.schedule(1000);
   }

   public void run() {
     doTheWork();
   }
 }
 
The above code coalesces all events that arrive in 1s and for all of them does doTheWork just once.
Interruption of tasks
Since version 6.3 there is a conditional support for interruption of long running tasks. There always was a way to cancel not yet running task using RequestProcessor.Task.cancel() but if the task's run() method was already running, one was out of luck. Since version 6.3 the thread running the task is interrupted and the Runnable can check for that and terminate its execution sooner. In the runnable one shall check for thread interruption (done from RequestProcessor.Task.cancel()) and if true, return immediately as in this example:
 private static final RequestProcessor RP = new RequestProcessor("Interruptible", 1, true);
 public void run () {
     while (veryLongTimeLoop) {
       doAPieceOfIt ();

       if (Thread.interrupted ()) return;
     }
 }
 

Since org.openide.util, implements ScheduledExecutorService


Nested Class Summary
 class RequestProcessor.Task
          The task describing the request sent to the processor.
 
Constructor Summary
RequestProcessor()
          Creates new RequestProcessor with automatically assigned unique name.
RequestProcessor(Class<?> forClass)
          Convenience constructor for a new RequestProcessor with throughput 1.
RequestProcessor(String name)
          Creates a new named RequestProcessor with throughput 1.
RequestProcessor(String name, int throughput)
          Creates a new named RequestProcessor with defined throughput.
RequestProcessor(String name, int throughput, boolean interruptThread)
          Creates a new named RequestProcessor with defined throughput which can support interruption of the thread the processor runs in.
RequestProcessor(String name, int throughput, boolean interruptThread, boolean enableStackTraces)
          Creates a new named RequestProcessor that allows to disable stack trace filling.
 
Method Summary
 boolean awaitTermination(long timeout, TimeUnit unit)
          
 RequestProcessor.Task create(Runnable run)
          Creates request that can be later started by setting its delay.
 RequestProcessor.Task create(Runnable run, boolean initiallyFinished)
          Creates request that can be later started by setting its delay.
static RequestProcessor.Task createRequest(Runnable run)
          Deprecated. Sharing of one singlethreaded RequestProcessor among different users and posting even blocking requests is inherently deadlock-prone. See use cases.
 void execute(Runnable command)
          Implements contract of Executor.
static RequestProcessor getDefault()
          Warning: The instance of RequestProcessor returned by this method has very bad performance side effects, don't use unless you understand all implications!
<T> List<Future<T>>
invokeAll(Collection<? extends Callable<T>> tasks)
          
<T> List<Future<T>>
invokeAll(Collection<? extends Callable<T>> tasks, long timeout, 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.

<T> T
invokeAny(Collection<? extends Callable<T>> tasks)
          

Executes the given tasks, returning the result of one which has completed and cancelling any incomplete tasks.

<T> T
invokeAny(Collection<? extends Callable<T>> tasks, long timeout, 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.

 boolean isRequestProcessorThread()
          Tests if the current thread is request processor thread.
 boolean isShutdown()
          
 boolean isTerminated()
          
 RequestProcessor.Task post(Runnable run)
          This methods asks the request processor to start given runnable immediately.
 RequestProcessor.Task post(Runnable run, int timeToWait)
          This methods asks the request processor to start given runnable after timeToWait milliseconds.
 RequestProcessor.Task post(Runnable run, int timeToWait, int priority)
          This methods asks the request processor to start given runnable after timeToWait milliseconds.
static RequestProcessor.Task postRequest(Runnable run)
          Deprecated. Sharing of one singlethreaded RequestProcessor among different users and posting even blocking requests is inherently deadlock-prone. See use cases.
static RequestProcessor.Task postRequest(Runnable run, int timeToWait)
          Deprecated. Sharing of one singlethreaded RequestProcessor among different users and posting even blocking requests is inherently deadlock-prone. See use cases.
static RequestProcessor.Task postRequest(Runnable run, int timeToWait, int priority)
          Deprecated. Sharing of one singlethreaded RequestProcessor among different users and posting even blocking requests is inherently deadlock-prone. See use cases.
<T> ScheduledFuture<T>
schedule(Callable<T> callable, long delay, TimeUnit unit)
          
 ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit)
          
 ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
          

Schedules a runnable which will run with a given frequency, regardless of how long execution takes, with the exception that if execution takes longer than the specified delay, execution will be delayed but will never be run on two threads concurrently.

 ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)
          

Schedules a runnable which will run repeatedly after the specified initial delay, with the specified delay between the completion of one run and the start of the next.

 void shutdown()
          
 List<Runnable> shutdownNow()
          
 void stop()
          Stops processing of runnables processor.
<T> Future<T>
submit(Callable<T> task)
          

Note: If the passed Callable implements Cancellable, then that object's Cancellable.cancel() method will be called if Future.cancel(boolean) is invoked.

 Future<?> submit(Runnable task)
          

Note: If the passed Runnable implements Cancellable, then that object's Cancellable.cancel() method will be called if Future.cancel(boolean) is invoked.

<T> Future<T>
submit(Runnable task, T predefinedResult)
           Note: If the passed Runnable implements Cancellable, then that object's Cancellable.cancel() method will be called if Future.cancel(boolean) is invoked.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

RequestProcessor

public RequestProcessor()
Creates new RequestProcessor with automatically assigned unique name.


RequestProcessor

public RequestProcessor(String name)
Creates a new named RequestProcessor with throughput 1.

Parameters:
name - the name to use for the request processor thread

RequestProcessor

public RequestProcessor(Class<?> forClass)
Convenience constructor for a new RequestProcessor with throughput 1. Typical usage is:
 class MyClass {
   private static final RequestProcessor RP = new RequestProcessor(MyClass.class);
 
 }
 
Behaves as new RequestProcessor(MyClass.class.getName()).

Parameters:
forClass - name of this class gives name for the processor threads
Since:
8.6

RequestProcessor

public RequestProcessor(String name,
                        int throughput)
Creates a new named RequestProcessor with defined throughput.

Parameters:
name - the name to use for the request processor thread
throughput - the maximal count of requests allowed to run in parallel
Since:
OpenAPI version 2.12

RequestProcessor

public RequestProcessor(String name,
                        int throughput,
                        boolean interruptThread)
Creates a new named RequestProcessor with defined throughput which can support interruption of the thread the processor runs in. There always was a way how to cancel not yet running task using RequestProcessor.Task.cancel() but if the task was already running, one was out of luck. With this constructor one can create a RequestProcessor which threads thread running tasks are interrupted and the Runnable can check for that and terminate its execution sooner. In the runnable one shall check for thread interruption (done from RequestProcessor.Task.cancel()) and if true, return immediatelly as in this example:
 public void run () {
     while (veryLongTimeLook) {
       doAPieceOfIt ();

       if (Thread.interrupted ()) return;
     }
 }
 

Parameters:
name - the name to use for the request processor thread
throughput - the maximal count of requests allowed to run in parallel
interruptThread - true if RequestProcessor.Task.cancel() shall interrupt the thread
Since:
6.3

RequestProcessor

public RequestProcessor(String name,
                        int throughput,
                        boolean interruptThread,
                        boolean enableStackTraces)
Creates a new named RequestProcessor that allows to disable stack trace filling. By default, when assertions are on, each task posted on RequestProcessor stores the stack trace at the time of posting. When an exception is later thrown from the task, it allows to print not only stack trace of the task but also stack trace of the code that posted it. However this may be a performance bottleneck in cases when hundreds of short task are scheduled. This constructor then allows to create RequestProcessor which never stores stack traces at the time of posting.

See constructor RequestProcessor(String, int, boolean) for details of interruptThread parameter.

Parameters:
name - the name to use for the request processor thread
throughput - the maximal count of requests allowed to run in parallel
interruptThread - true if RequestProcessor.Task.cancel() shall interrupt the thread
enableStackTraces - false when request processor should not fill stack traces when task is posted. Default is true when assertions are enabled, false otherwise.
Since:
7.24
Method Detail

getDefault

public static RequestProcessor getDefault()
Warning: The instance of RequestProcessor returned by this method has very bad performance side effects, don't use unless you understand all implications!

This is the getter for the shared instance of the RequestProcessor. This instance is shared by anybody who needs a way of performing sporadic asynchronous work.

The problem of this method lays exactly in the definition of sporadic. Often one needs to process something at some sporadic moment, but, for examle due to storm of events, one needs to execute more than one tasks at the same sporadic moment. In this situation using getDefault() is horribly inefficient. All such tasks would be processed in parallel, allocating their own execution threads (up to 50). As the price per one thread is estimated to 1MB on common systems, you shall think twice whether you want to increase the memory consumption of your application so much at these sporadic moments.

There is a runtime detection of the parallel misuse of this method since version 8.3. It is activated only in development mode (when executed with assertions on) and prints warning into log whenever there are more than three same tasks running in parallel. In case you see such warning, or in case you are in doubts consider creation of your own, private, single throughput processor:

 class YourClass {
   private static final RequestProcessor RP = new RequestProcessor(YourClass.class);
 }
 
Such private field is lightweight and guarantees that all your tasks will be processed sequentially, one by one. Just don't forget to make the field static!

Tasks posted to this instance may be canceled until they start their execution. If a there is a need to cancel a task while it is running a seperate request processor needs to be created via RequestProcessor(String, int, boolean) constructor.

Returns:
an instance of RequestProcessor that is capable of performing "unlimited" (currently limited to 50, just for case of misuse) number of requests in parallel.
Since:
version 2.12
See Also:
RequestProcessor(String, int, boolean), RequestProcessor.Task.cancel()

execute

public void execute(Runnable command)
Implements contract of Executor. Simply delegates to post(java.lang.Runnable).

Specified by:
execute in interface Executor
Parameters:
command - the runnable to execute
Since:
7.16

post

public RequestProcessor.Task post(Runnable run)
This methods asks the request processor to start given runnable immediately. The default priority is Thread.MIN_PRIORITY.

Parameters:
run - class to run
Returns:
the task to control the request

post

public RequestProcessor.Task post(Runnable run,
                                  int timeToWait)
This methods asks the request processor to start given runnable after timeToWait milliseconds. The default priority is Thread.MIN_PRIORITY.

Parameters:
run - class to run
timeToWait - to wait before execution
Returns:
the task to control the request

post

public RequestProcessor.Task post(Runnable run,
                                  int timeToWait,
                                  int priority)
This methods asks the request processor to start given runnable after timeToWait milliseconds. Given priority is assigned to the request.

For request relaying please consider:

    post(run, timeToWait, Thread.currentThread().getPriority());
 

Parameters:
run - class to run
timeToWait - to wait before execution
priority - the priority from Thread.MIN_PRIORITY to Thread.MAX_PRIORITY
Returns:
the task to control the request

create

public RequestProcessor.Task create(Runnable run)
Creates request that can be later started by setting its delay. The request is not immediatelly put into the queue. It is planned after setting its delay by schedule method. By default the initial state of the task is !isFinished() so doing waitFinished() will block on and wait until the task is scheduled.

Parameters:
run - action to run in the process
Returns:
the task to control execution of given action

create

public RequestProcessor.Task create(Runnable run,
                                    boolean initiallyFinished)
Creates request that can be later started by setting its delay. The request is not immediatelly put into the queue. It is planned after setting its delay by schedule method.

Parameters:
run - action to run in the process
initiallyFinished - should the task be marked initially finished? If so the RequestProcessor.Task.waitFinished() on the task will succeeded immediatelly even the task has not yet been RequestProcessor.Task.schedule(int)d.
Returns:
the task to control execution of given action
Since:
6.8

isRequestProcessorThread

public boolean isRequestProcessorThread()
Tests if the current thread is request processor thread. This method could be used to prevent the deadlocks using waitFinished method. Any two tasks created by request processor must not wait for themself.

Returns:
true if the current thread is request processor thread, otherwise false

stop

public void stop()
Stops processing of runnables processor. The currently running runnable is finished and no new is started.


postRequest

@Deprecated
public static RequestProcessor.Task postRequest(Runnable run)
Deprecated. Sharing of one singlethreaded RequestProcessor among different users and posting even blocking requests is inherently deadlock-prone. See use cases.

This methods asks the request processor to start given runnable after timeToWait milliseconds. The default priority is Thread.MIN_PRIORITY.

Parameters:
run - class to run
Returns:
the task to control the request

postRequest

@Deprecated
public static RequestProcessor.Task postRequest(Runnable run,
                                                           int timeToWait)
Deprecated. Sharing of one singlethreaded RequestProcessor among different users and posting even blocking requests is inherently deadlock-prone. See use cases.

This methods asks the request processor to start given runnable after timeToWait milliseconds. The default priority is Thread.MIN_PRIORITY.

Parameters:
run - class to run
timeToWait - to wait before execution
Returns:
the task to control the request

postRequest

@Deprecated
public static RequestProcessor.Task postRequest(Runnable run,
                                                           int timeToWait,
                                                           int priority)
Deprecated. Sharing of one singlethreaded RequestProcessor among different users and posting even blocking requests is inherently deadlock-prone. See use cases.

This methods asks the request processor to start given runnable after timeToWait milliseconds. Given priority is assigned to the request.

Parameters:
run - class to run
timeToWait - to wait before execution
priority - the priority from Thread.MIN_PRIORITY to Thread.MAX_PRIORITY
Returns:
the task to control the request

createRequest

@Deprecated
public static RequestProcessor.Task createRequest(Runnable run)
Deprecated. Sharing of one singlethreaded RequestProcessor among different users and posting even blocking requests is inherently deadlock-prone. See use cases.

Creates request that can be later started by setting its delay. The request is not immediatelly put into the queue. It is planned after setting its delay by setDelay method.

Parameters:
run - action to run in the process
Returns:
the task to control execution of given action

shutdown

public void shutdown()

Specified by:
shutdown in interface ExecutorService
Throws:
an - IllegalStateException if called on the default request processor
Since:
org.openide.util 8.2

shutdownNow

public List<Runnable> shutdownNow()

Specified by:
shutdownNow in interface ExecutorService
Throws:
an - IllegalStateException if called on the default request processor
Since:
org.openide.util 8.2

isShutdown

public boolean isShutdown()

Specified by:
isShutdown in interface ExecutorService
Since:
org.openide.util 8.2

isTerminated

public boolean isTerminated()

Specified by:
isTerminated in interface ExecutorService
Since:
org.openide.util 8.2

awaitTermination

public boolean awaitTermination(long timeout,
                                TimeUnit unit)
                         throws InterruptedException

Specified by:
awaitTermination in interface ExecutorService
Throws:
InterruptedException
Since:
org.openide.util 8.2

submit

public <T> Future<T> submit(Callable<T> task)

Note: If the passed Callable implements Cancellable, then that object's Cancellable.cancel() method will be called if Future.cancel(boolean) is invoked. If Cancellable.cancel() returns false, then the job will not be cancelled.

Specified by:
submit in interface ExecutorService
Since:
org.openide.util 8.2

submit

public <T> Future<T> submit(Runnable task,
                            T predefinedResult)
Note: If the passed Runnable implements Cancellable, then that object's Cancellable.cancel() method will be called if Future.cancel(boolean) is invoked. If Cancellable.cancel() returns false, then the job will not be cancelled.

Specified by:
submit in interface ExecutorService
Since:
org.openide.util 8.2

submit

public Future<?> submit(Runnable task)

Note: If the passed Runnable implements Cancellable, then that object's Cancellable.cancel() method will be called if Future.cancel(boolean) is invoked. If Cancellable.cancel() returns false, then the job will not be cancelled.

Specified by:
submit in interface ExecutorService
Since:
org.openide.util 8.2

invokeAll

public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
                          throws InterruptedException

Specified by:
invokeAll in interface ExecutorService
Throws:
InterruptedException
Since:
org.openide.util 8.2

invokeAll

public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
                                     long timeout,
                                     TimeUnit unit)
                          throws 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.

Specified by:
invokeAll in interface ExecutorService
Throws:
InterruptedException
Since:
org.openide.util 8.2

invokeAny

public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
            throws InterruptedException,
                   ExecutionException

Executes the given tasks, returning the result of one which has completed and cancelling any incomplete tasks.

Specified by:
invokeAny in interface ExecutorService
Throws:
InterruptedException
ExecutionException
Since:
org.openide.util 8.2

invokeAny

public <T> T invokeAny(Collection<? extends Callable<T>> tasks,
                       long timeout,
                       TimeUnit unit)
            throws InterruptedException,
                   ExecutionException,
                   TimeoutException

Executes the given tasks, returning a list of Futures holding their status and results when all complete or the timeout expires, whichever happens first.

Specified by:
invokeAny in interface ExecutorService
Type Parameters:
T - The result type
Parameters:
tasks - A collection of callables
timeout - The maximum time to wait for completion, in the specified time units
unit - The time unit
Returns:
A list of futures
Throws:
InterruptedException - if the timeout expires or execution is interrupted
ExecutionException
TimeoutException
Since:
org.openide.util 8.2

schedule

public ScheduledFuture<?> schedule(Runnable command,
                                   long delay,
                                   TimeUnit unit)

Specified by:
schedule in interface ScheduledExecutorService
Since:
org.openide.util 8.2

schedule

public <T> ScheduledFuture<T> schedule(Callable<T> callable,
                                       long delay,
                                       TimeUnit unit)

Specified by:
schedule in interface ScheduledExecutorService
Since:
org.openide.util 8.2

scheduleAtFixedRate

public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
                                              long initialDelay,
                                              long period,
                                              TimeUnit unit)

Schedules a runnable which will run with a given frequency, regardless of how long execution takes, with the exception that if execution takes longer than the specified delay, execution will be delayed but will never be run on two threads concurrently.

Specified by:
scheduleAtFixedRate in interface ScheduledExecutorService
Since:
org.openide.util 8.2

scheduleWithFixedDelay

public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
                                                 long initialDelay,
                                                 long delay,
                                                 TimeUnit unit)

Schedules a runnable which will run repeatedly after the specified initial delay, with the specified delay between the completion of one run and the start of the next.

Specified by:
scheduleWithFixedDelay in interface ScheduledExecutorService
Since:
org.openide.util 8.2

org.openide.util 8.19.1

Built on December 7 2011.  |  Portions Copyright 1997-2011 Oracle. All rights reserved.