|
|||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||
java.lang.Objectcom.databasesandlife.util.AutoStopThreadPool
public class AutoStopThreadPool
A pool of threads which execute tasks, and which will shut down after all tasks have been completed. Tasks, during their execution, may schedule further tasks for execution.
Firstly the object is created, and then tasks are added using the addTask method.
(These tasks, when executed, may add other tasks, also using the addTask method.)
The execute method is then called; this starts the threads and returns when all tasks (and tasks created by
those tasks) have been completed.
String name = "my-task"; // Thread name; visible in debugger
int workerThreadCount = 4;
final AutoStopThreadPool pool = new AutoStopThreadPool(name, workerThreadCount);
pool.addTask(new Runnable() { ....; if (..) pool.addTask(...); });
pool.execute(); // Blocks until all tasks completed; rethrows any exception thrown by a task
The threads are only created when the execute method is called: if they were started when the object was instanciated
then they would stop again immediately due to there being no tasks at that point in time.
There is no way to specify a maximum size of the queue of tasks. The queue of tasks to be executed is necessarily unbounded: if it had a fixed size, and adding a new task would block until space was available, and the entity adding the task was itself a task, deadlock could occur. If there were n threads, the queue was full, and all n threads tried to add new tasks, then they would all block waiting for space to be available in the queue, yet space would never become available as all tasks would be waiting.
Thread pools such as ExecutorService offered by the JVM have two phases:
The object is named after cassette players which boast the feature "auto stop", meaning they stop automatically once the cassette is finished.
| Constructor Summary | |
|---|---|
AutoStopThreadPool(String name,
int workerThreadCount)
|
|
| Method Summary | |
|---|---|
void |
addTask(Runnable r)
Add this runnable to the queue of tasks to be executed. |
void |
execute()
Starts the threads and execute all tasks, returning once they have all been completed. |
| Methods inherited from class java.lang.Object |
|---|
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Constructor Detail |
|---|
public AutoStopThreadPool(String name,
int workerThreadCount)
| Method Detail |
|---|
public void addTask(Runnable r)
execute method is called.
public void execute()
RuntimeException - if a task has thrown an exception.
(Regrettably checked exceptions cannot be safely or usefully thrown,
more info)
|
|||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | ||||||||