2017-09-29 4 views
3

Ich schrieb eine einzige statische Instanz in Java:Verschiedene Java API verwenden unterschiedliche statische Speicher?

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

} 

und Verwendung:

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

} 

// Es funktioniert gut, wenn ich eine einzelne api getConnection method.But verwenden rufen nach // ich eine andere nennen api mit gleichem signKey, SocketMap zeigt nichts.

Es ist mein Fehler.Ich habe den Socket zweimal nach der Trennung entfernt, nur ein statischer Speicher ist die Wahrheit.

+3

I‘ Ich stimme, um diese Frage als Off-Thema zu schließen, weil der Benutzer seine eigenen Fragen beantwortet (letzte Zeile) –

Antwort

1

Sind Sie auf der Suche nach einem Code etwas wie unten? (Änderte ich den Parameter token mit 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; 
     } 
    } 
} 

Dies druckt immer ‚ich den gleichen Wert habe‘

Ist dies nicht hilfreich ist, teilen Sie bitte die Art und Weise Sie anrufen, um getConnection

+0

Thanks.It ist meine Schuld.Ich habe Doppel-Socket nach Socket trennen entfernt. – Lyle

Verwandte Themen