Task Execution
In Same Thread
To run a task in the current thread, you do this:
Callable<String> mytask = new MyTask(); String result = TaskExecutor.execute(mytask);
In New Thread
To run a task in a new thread, and block this thread until the task is complete, you do this:
Callable<String> mytask = new MyTask(); TaskFuture<String> future = TaskExecutor.start(mytask); String result = future.get();
When started that way, the task can be easily stopped:
Callable<String> mytask = new Tasks.MyTask(); TaskFuture<String> future = TaskExecutor.start(mytask); // logic that decides to stop the task future.cancel(true);
Alternatively, if the task supports pausing, it can be paused and restarted as follows:
Callable<String> mytask = new Tasks.MyTask(); TaskFuture<String> future = TaskExecutor.start(mytask); // logic that decides to pause the task future.pause(); // logic that decides when to restart the task future.unpause();
Advanced
More advanced control over how tasks are set up and started, can be obtained
via use of the prepare()
method. This allows you to control the
state of the task or tasks prior to starting execution.
This prepares a task for synchronous (same thread) execution and then starts it running and gets its result:
Callable<String> mytask = new Tasks.MyTask(); StartableTaskFuture<String> startableFuture = TaskExecutor.prepare(false, "MyThread1", mytask); // execute immediately in current thread TaskFuture<String> future = startableFuture.start(); // fetch already available result String result = future.get();
This prepares a task for asynchronous (separate thread) execution and then starts it running and waits for its result:
Callable<String> mytask = new Tasks.MyTask(); StartableTaskFuture<String> startableFuture = TaskExecutor.prepare(true, "MyThread1", mytask); // start off a new thread TaskFuture<String> future = startableFuture.start(); // blocks until complete String result = future.get();
The following example performs a "gunshot" start of the tasks,
executing them asynchronously. The call to prepare()
creates the Thread
object and executes any
@Init
methods:
Listmytasks = new ArrayList (); List startableFutures = new ArrayList (); for (Callable<String> task: mytasks) { StartableTaskFuture<String> future = TaskExecutor.prepare(true, task); startableFutures.add(future); } for (StartableTaskFuture<String> future: startableFutures) { future.start(); }