I wrote a single static instance in Java:
public class SocketMap {
private static SocketMap instance = new SocketMap();
public static SocketMap getInstance(){
return instance;
}
static Map<String, Socket> socketMap = new HashMap<>();
public static Map<String, Socket> getSocketMap() {
return socketMap;
}
}
And use:
public Socket getConnection(String token, String signKey) {
synchronized (lock) {
if (SocketMap.getSocketMap().containsKey(signKey)){//single api will went here
return SocketMap.getSocketMap().get(signKey);
}
else {//second api will went here first
//todoSocket
SocketMap.getSocketMap().put(signKey, socket);
System.out.print("new Socket");
return socket;
}
}
}
//It works fine when I call a single api use getConnection method.But after //I call another api with same signKey, SocketMap shows nothing.
It's my Fault.I removed socket twice after disconnect;Only one static storage is truth.