Question

For my program I was using a ConcurrentHashMap to hold references to multiple running objects. In my server i have:

public class Server {

private ConcurrentHashMap<String, ChatRoom> _chatRooms;
private ExecutorService _chatRoomExecutor;
...

// create a new channel executor to handle 50 chatrooms
_chatRoomExecutor= Executors.newFixedThreadPool(50);
// create an admin chatroom for testing at this point
_chatRooms.put("/admin", new Channel("/admin"));
// execute that chatroom
_chatRoomExecutor.execute(_chatRooms.get("/admin"));

would this work as I could still access the chatroom from the ConcurrentHashMap or would I have to do something with the threadpool?

Était-ce utile?

La solution

would this work as I could still access the chatroom from the ConcurrentHashMap or would I have to do something with the threadpool?

Yes your code should work fine. However, you need to make sure that you are properly synchronizing on the fields in your ChatRoom objects since they will be accessed both from their run() method by the thread-pool threads as well as from the outside thread(s) by getting the objects from the ConcurrentHashMap. That's going to be your challenge.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top