2017-09-29 23 views
3

我寫在Java中一個靜態實例:不同的Java Api使用不同的靜態存儲?

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; 
    } 

} 

及用途:

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; 
      } 
     } 

} 

//它正常工作時,我叫一個單一的API使用的getConnection method.But //後,我調用另一個帶有相同signKey的api,SocketMap什麼都不顯示。

這是我的錯。斷開連接後我刪除了兩次套接字;只有一個靜態存儲是事實。

+3

我的方式m投票結束這個問題作爲題外話,因爲用戶回答他自己的問題(最後一行) –

回答

1

您是否在尋找類似於下面的代碼? (我改變了參數tokensocket

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; 
     } 
    } 
} 

這將始終打印「我得到了相同的價值」

如果這是沒有幫助的,請分享你打電話來getConnection

+0

Thanks.It是我的錯。 – Lyle