My program is a client connected to multiple servers. I save connection objects to all servers in a static map object:
server1 -> connection1
server2 -> connection2
serverN -> connectionN
public class CacheConnection {
private final static Map cacheConnection = new HashMap();
public static void add(String serverName, Socket sock) {
synchronized (cacheConnection) {
cacheConnection.put(serverName, sock);
}
}
public static Socket get(String serverName) {
return (Socket) cacheConnection.get(serverName);
}
..
}
I have many threads getting connections from this map to communicate with the servers. How can I ensure a connection can only be used by one thread at a time?
For example, I want to be sure thread 1 and thread 2 cannot use connection 1 at the same time.
I am not completely sure, what you want. I assume that you want to guarantee that only one thread at a time accesses one particular server.
If your connection is something like a socket, then you can use it as a lock in a synchronization statement:
You can put the logic also into a decorator for the connection. This is especially useful if your connection has more than one method that send or receive (e.g., because you use a higher abstraction level like RMI):
If you are using the decorator approach, then the only thing you need to change is the instance creation. Instead of:
use