Different Java Api use different static storage?

Viewed 36

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.

1 Answers

Are you looking for a code something like below? (I changed the parameter token with socket

public void testMethod(){
    Socket s = new Socket();
    Socket s1 = getConnection(s, "firstKey");
    Socket s2 = getConnection(s, "firstKey");
    if(s1 == s2){
        System.out.println("I got the same value");
    }else{
        System.out.println("I got the different value");
    }
}

 public Socket getConnection(Socket socket, 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.println("new Socket");
            return socket;
        }
    }
 }

This will always print 'I got the same value'

If this is not helpful, please share the way you are calling to getConnection

Related