2013-04-08 2 views
0

지도를 마무리하는 클래스가 있습니다. 지도는 아래와 같이 Add() 및 isUpwardTrade() 메소드를 사용하여 읽고 쓸 수 있습니다.스레드 안전 HashMap 액세스

전체 메서드를 동기화하여 스레드 안전 문제가 있습니까? 다중 스레드 컨텍스트에서 성능을 향상 시키려면 다음 구현 (예 : concurrentHashMap 또는 다른 것을 사용 하시겠습니까?)을 어떻게 변경 하시겠습니까?

private Map<String, List<Double>> priceTable = new HashMap<String, List<Double>>(); 
private AutoTrader autoTrader; 

public PriceTable(AutoTrader autoTrader) { 
    this.autoTrader = autoTrader; 
} 

public synchronized void add(Price price) {  
    if (!priceTable.containsKey(price.getProductName())){ 
     List<Double> prices = new ArrayList<Double>(); 
     Double pValue = price.getPrice(); 
     prices.add(pValue); 
     priceTable.put(price.getProductName(), prices); 
    }else{ 
     Double pValue = price.getPrice(); 
     priceTable.get(price.getProductName()).add(pValue); 
    } 

    if (isUpwardTrend(price, priceTable)) { 
     notifyAutoTrader(price); 
    } 
} 

private void notifyAutoTrader(Price price) { 
    autoTrader.onUpwardTrendEvent(price); 
} 

private synchronized boolean isUpwardTrend(Price price, Map<String, List<Double>> pricesTable) { 
    List<Double> prices = priceTable.get(price.getProductName()); 
    if (prices.size() >= 4){ 
     if (calcAvg(prices) > prices.get(prices.size() - 4)) 
      return true; 
    } 
    return false; 
} 

답변

0

해시 맵은 threadsafe가 아닙니다. ConcurrentHashMap 또는 Hashtable을 사용해야합니다.

+0

물론지도를 읽거나 쓰는 방법을 동기화하고 있습니다. –

+0

나는 본다. HashMap에 액세스하는 유일한 메소드가 동기화되었으므로 코드가 안전합니다. Hashtable과 같은 스레드 세이프 (thread safe) 객체를 사용한다면 동기화가 객체에 구현됩니다. 귀하의 코드는 래퍼에서 동기화를 구현합니다. – zaz