My situation is as follows, I have a lot of objects and each of them needs to be associate with a separate thread. When the object is discarded, the corresponding thread needs to be terminated as well. Consider the situation like there are a lot of robots running independently in some maze, some of them may die after a while, their corresponding threads need to be removed.
so here is some sample code for creating the objects and threads(it could be done in a different way as the object wrapper described later),
List<MyObject> objects = new ArrayList();
List<Thread> threads = new ArrayList();
for(int i = 0; i < 10000/* could be arbitrary large number*/; i++){
MyObject obj = new MyObject();
threads.add(new Thread(){
@Override
public void run(){
// do something with obj
}
});
}
Once the object is removed from the list, the thread should also be terminated, so here I have an intuitive idea that I create a map as the Thread Manager to manage this,
List<MyObject> objects = new ArrayList();
List<Thread> threads = new ArrayList();
Map<MyObject, Thread> threadManager = new HashMap();
for(int i = 0; i < 10000/* could be arbitrary large number*/; i++){
MyObject obj = new MyObject();
Thread thread = new Thread(){
@Override
public void run(){
// do something with obj
}
};
threads.add(thread);
threadManager.put(obj, thread);
}
So now if the obj is removed from the list, I can find the entry in the map and stop the thread. Another idea would be create the object as a Runnable, so this object would be a wrapper for the thread.
public class MyObject implements Runnable {
private volatile flag = true;
public void run(){
while(flag){//do somehting}
}
public void shutdown(){
flag = false;
}
}
So when the obj is removed from the list, just call shutdown for it.
So my question would be which one is better? Is there more elegant way to do this?