In my application I keep track of the running threads via a hash map, in that way I can retrieve the correct thread and do any actions. The app evolved in a way that new threads are created and old threads must be destroyed. My concern is if I’m removing the elements of the hash correctly, or if there’s any efficient pattern.
I’m developing in Java but I’ll share the pseudo code:
# HashMap mainHashmap already initialized
List toDelete = new List();
# First step, stop the threads
For (each element in HashMap)
{
if (element.value is ThreadA)
{
element.value.stopThread();
toDelete.add(element.key);
}
}
# Then remove the element from the array
For (each key in toDelete)
{
mainHashmap.remove(key);
}
Thanks
5
A couple problems I can see with this are the following:
-
Stopping a thread like this is dangerous since you have no idea what it is doing in that particular moment. Usually in a situation like this you’d send it a message asking it to stop when it’s convenient, and the thread can stop in its own way (closing resources and connections, etc.). Once each thread is stopped (when the callback indicating that it has stopped is called), then you can take the proper action of removing it from your hash map.
-
The second problem is a little more subtle. I see no locks here, so I have to assume there are none. You have to be sure that this method cannot be run while another thread is running it or you get all sorts of problems which seem to happen only once in a while in random moments. In general, any access to this hash map should be locked or should not be public and the methods you use to access it are locked.
If the threads being run are your own, and you’re fairly confident that these threads can be stopped on a dime, then #1 is not a problem, however know that it is an anti-pattern. Most languages support stopping a thread abruptly only because it should still exist as a last resort option, but you would normally ask nicely if the thread could please stop for you. If the thread ignores the request (especially these threads are not running code you’ve made yourself), you can then consider the possibility of outright stopping the thread.
I can’t get too specific because it really depends on the language that you’re using, but most languages have a proper “done” method which gets executed upon finish (or halt), and you could take advantage of this method by calling the thread pool with that instance to indicate that the thread is stopped and can be removed.
3