im working on a thread pool(TP) implementation, but im having problems finding a way to kill (i.e. remove) an inactive thread (i.e. worker).
When my TP is started I initialize a number of workers. After a period of time (or when something happends) I'd like to be able remove 1 inactive thread. Im not quite sure what to put in my "removeThread()" method.
Basicly I've got some threads floating around; sometimes doing some work and sometimes waiting.. so I dont really know how I can get hold of one of them so I can "kill it".
Hmm, this is clearly related to this thread, though you're now asking a different question (despite reusing the exact same thread title, which is a bit confusing). Anyway, people can refer to the earlier thread for additional details.
I wonder if you could queue up a job that does nothing but interrupt() itself. Your Worker would check for interrupted() and exit the run() loop.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Joined: Jan 30, 2000
I'm not sure what's in your thread pool implementation so far, but I would think that you must have one or more collections containing references to all the threads in the pool, and some way to tell which threads are currently assigned to some task, and which are not. One way to achieve this would be to have two Sets of WorkerThreads, one named activeWorkers, and the other, inactiveWorkers. To start a task, remove a thread from inactiveWorkers (or block until one is available), add it to activeWorkers, and assign it the new task. When a task ends, move the worker from active to inactive.
To remove a thread entirely, remove it from inactive - now it won't be used again. You will probably also need to call some method on the WorkerThread, because each WorkerThread probably has some sort of while loop and a wait/notify protocol to keep it looping, waiting for a new task, running the task, then waiting again. You can probably break out of this by simply calling interrupt(), if you place your InterruptedException catch block correctly.
If this doesn't make sense, you may well need to post some more code showing how your thread pool actually works. Hope that helps...
I am assuming that (in your implementation of the threadpool) you have some kind of notification technique to inform the waiting threads that a job is available... for example... When a thread finish a job, they check for new jobs. If none is available, they wait until they get a notification. On the other side, when a new job is added, a notification is sent.
The modification could simply be setting some sort of exiting flag, and sending a notifyAll. On the other side, upon wakeup, or after finishing the job, the threads can check to see if it should exit, by checking the flag.
Henry [ August 28, 2006: Message edited by: Henry Wong ]