Thread safety 线程安全哈希映射访问

Thread safety 线程安全哈希映射访问,thread-safety,hashmap,synchronized,Thread Safety,Hashmap,Synchronized,我有一门课,它会画一张地图。该映射由Add()和isUpwardTrade()方法读/写,如下所示 通过同步整个方法,您是否发现任何线程安全问题? 您将如何更改以下实现(即,您会使用concurrentHashMap或其他什么?)以提高多线程环境中的性能 private Map<String, List<Double>> priceTable = new HashMap<String, List<Double>>(); private AutoTr

我有一门课,它会画一张地图。该映射由Add()和isUpwardTrade()方法读/写,如下所示

通过同步整个方法,您是否发现任何线程安全问题? 您将如何更改以下实现(即,您会使用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;
}
private Map priceTable=new HashMap();
专用自动雷达自动雷达;
公共价格表(自动转换器自动转换器){
this.autoTrader=autoTrader;
}
公共同步无效添加(价格){
如果(!priceTable.containsKey(price.getProductName())){
标价=新的ArrayList();
Double pValue=price.getPrice();
价格。添加(pValue);
priceTable.put(price.getProductName(),prices);
}否则{
Double pValue=price.getPrice();
priceTable.get(price.getProductName()).add(pValue);
}
如果(是上升趋势(价格,价格表)){
自动雷达(价格);
}
}
专用自动雷达(价格){
autoTrader.onUpwardTrendEvent(价格);
}
private synchronized boolean isUpwardTrend(价格、地图价格稳定){
标价=priceTable.get(price.getProductName());
如果(prices.size()>=4){
if(calcAvg(prices)>prices.get(prices.size()-4))
返回true;
}
返回false;
}

哈希映射不是线程安全的。
您应该使用ConcurrentHashMap或Hashtable。

当然可以,但我正在同步读取/写入映射的方法。我明白了。因为只有访问HashMap的方法是同步的,所以您的代码是安全的。如果您使用的是像Hashtable这样的线程安全对象,那么同步将在该对象中实现。代码在包装器中实现同步。