【问题标题】:Thread-safe HashMap access线程安全的 HashMap 访问
【发布时间】:2013-04-08 00:47:13
【问题描述】:

我有一个包裹地图的类。地图由 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;
}

【问题讨论】:

    标签: thread-safety hashmap synchronized


    【解决方案1】:

    Hashmap 不是线程安全的。 您应该使用 ConcurrentHashMap 或 Hashtable。

    【讨论】:

    • 当然,但我正在同步读/写地图的方法。
    • 我明白了。由于访问 HashMap 的唯一方法是同步的,因此您的代码是安全的。如果您使用像 Hashtable 这样的线程安全对象,则同步将在对象中实现。您的代码在包装器中实现了同步。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多