I store threads in a container. With time, some of these threads will be running, and some of these will be dead. What i want to achieve is: automatically (or periodically) remove the dead (stopped) threads from the container.
What is the best way to do this?
Edit: I store my threads in a simple linked-list:
LinkedList<ServerThread> threadPool = new LinkedList<ServerThread>();
This container have to be dynamic, because with time, i have to add (and obviously delete) threads.
EDIT2: This is how i currently manage threads. As you can see, i wait for incoming connections, i don’t know when it will arrive, but when it does, i have to handle it in a new thread.
while (!interrupted()) {
try {
Socket clientSocket = serverSocket.accept();
if (portNumber == Server.SMTP_PORT_NUMBER) {
threadPool.add(new SMTPThread(clientSocket, db));
threadPool.getLast().setName("SMTP Thread " + ++threadCounter);
} else {
threadPool.add(new POP3Thread(clientSocket, db));
threadPool.getLast().setName("POP3 Thread " + ++threadCounter);
}
threadPool.get(threadPool.size() - 1).start();
} catch (SocketTimeoutException e) {
} catch (IOException ioe) {
}
}
You should not maintaining your own list of threads unless there are specific reasons to do so. I’d recommend using the excellent
ExcecutorServiceclasses that have been available since Java 5. Something like the following:The thread-pool will take care of maintaining the running threads in the pool. The threads will be re-used on the next job and will be shutdown when there are no more jobs in the pool and it has been shutdown. You won’t need to reap any dead threads yourself.
Edit:
In terms of the code you posted, to remove finished threads from your pool you should just run through them like:
I’d do this after each time you add a new thread to the pool. Also, remember that
LinkedListis not efficient to do aget(#)method call. I’d recommend you tweak your code to do: