2015-01-25 3 views
0

테이블이있는 싱글 톤 개체 (클래스)가 있습니다 (해시 맵). 다른 모든 개체 (클라이언트)는 테이블에 저장된 다른 클라이언트의 목록을 읽습니다. 테이블을 사용하는 모든 메소드는 synchronized 키워드로 둘러 쌓여 있습니다. 다른 클라이언트에 대해 테이블의 값이 다른 상황을 디버깅했습니다. 클라이언트는 동기화 된 키워드를 추가 한 이유와 동일한 스레드에서 실행되고있을 수도 있고 실행되지 않을 수도 있습니다.자바 동기화 및 공유 테이블

Client temp=AppInterface.getInstance().getAppNetworkLogic().getFromConnectedClients(key); 

AppNetowrkLogicAppInterface 싱글과 내부 목적 : 나 클라이언트 개체 내부 테이블에 액세스하는 방법

여기
public synchronized Client addToConnectedClients(long key, Client client) 
{ 
    return allConnectedClients.put(key, client); 
} 

public synchronized Client getFromConnectedClients(long key) 
{ 
    return allConnectedClients.get(key); 
} 

public synchronized Client removeFromConnectedClients(long key) 
{ 
    return allConnectedClients.remove(key); 
} 

은 여기

는 해시 맵을 사용하는 방법이고 AppInterface이 만들어 질 때입니다.

어떻게 이런 일이 발생할 수 있는지 잘 모르겠습니다.

편집 :

private static AppInterface instance=null; 
public static AppInterface getInstance() 
{ 
    if(instance == null) 
    { 
     instance= new AppInterface(); 
    } 
    return instance;   
} 
+0

에 대한 액세스를 동기화? 거기에 경쟁 조건이 의심됩니다. – shazin

+1

나는 이것이 현재 싱글 톤 패턴이 enum 인 이유라고 생각한다. –

답변

1

나는 경쟁 조건이 발생할 수 있습니다 하나 이상의 AppInterface가 생성 될 수 getInstance 액세스하는 여러 클라이언트에 의해 경쟁 조건에서 의심 하듯이 : 여기 getInstance 방법이다.

어느 간절히 당신이) (AppInterface.getInstance에 대한 코드를 보여줄 수

private static AppInterface instance=new AppInterface(); 
public static AppInterface getInstance() 
{ 
    return instance;   
} 

AppInterface

만들거나 AppInterface

private static AppInterface instance=null; 
public static AppInterface getInstance() 
{ 
    synchronized(AppInterface.class) { 
     if(instance == null) 
     { 
      instance= new AppInterface(); 
     } 
    } 
    return instance;   
} 
+0

이 문제가 중요하지만 프로그램이 시작될 때 main 함수에'AppInterface'가 생성되면'AppInterface' 만 사용됩니다. 또한 문제는 많은 시간이 지난 후에 발생합니다. 또 다시 중요한지 모르겠다. – Maro

+0

@Maro 언제든지 테이블을 사용하십시오. 결과가 일관되지 않는 경우는,'getInstance' 메소드에 관련 지을 수 있습니다. @shazin 두 번째 방법은 스레드로부터 안전하지 않습니다. [double-checked locking]을 사용하십시오. (http://en.wikipedia.org/wiki/Double-checked_locking) – qqibrow

+0

@qqibrow 예. 이미 확인했지만 일관성이 없었습니다.하지만 AppInterface가 주요 기능과 문제가 오랜 시간 후에 발생합니다. 보통 두 개의 다른 쓰레드가 객체를 초기화하려고 시도 할 때 처음에'getInstance' 메쏘드의 문제가 발생합니다. 그러나 만약 쓰레드가 생성되기 전에 생성된다면 문제가 발생하지 않을 것입니다. – Maro