【问题标题】:One HashMap, two threads - how do I ensure thread-safety in this example?一个 HashMap,两个线程——在这个例子中我如何确保线程安全?
【发布时间】:2017-07-30 13:08:27
【问题描述】:

我有一个关于线程安全和 HashMaps 的问题。更具体地说,我想知道一个线程是否有可能在写入 HashMap 时尝试读取它。这是一个粗略的例子:

我有一个名为“TestClass”的类:

public class TestClass implements Runnable {

    // New thread
    TestThread testThread = new TestThread();

    @Override
    public void run() {

        // Starts the thread.
        testThread.start();

        // A copy of testHashMap is retrieved from the other thread.
        // This class often reads from the HashMap.
        // It's the only class that reads from the HashMap.
        while (true) {
            HashMap<String, Long> testHashMap = testThread.get();

        }
    }
}

我还有另一个名为 TestThread 的类:

public class TestThread extends Thread {

    private HashMap<String, Long> testHashMap = new HashMap<>();

    @Override
    public void run() {

        // This thread performs a series of calculations once a second.
        // After the calculations are done, they're saved to testHashMap with put().
        // This is the only thread that writes to testHashMap.

    }

    // This method returns a copy of testHashMap. This method is used by the Test class.
    public HashMap<String, Long> get() {
        return testHashMap;
    }

}

get() 方法是否有可能在 TestThread 写入时尝试复制 testHashMap?如果是这样,在这个例子中我如何确保线程安全?我必须创建一个同步映射而不是一个哈希映射吗?

提前致谢。

【问题讨论】:

标签: java hashmap thread-safety


【解决方案1】:

get() 方法是否有可能在 TestThread 写入时尝试复制 testHashMap?

没有。 get() 方法只返回地图。此处不进行复制。

但是是的,您必须以某种方式控制对地图的访问,因为HashMap 不是线程安全的。您可以通过同步哈希图 (Map&lt;A, B&gt; map = Collections.synchronizedMap(new HashMap&lt;A, B&gt;());) 或使用 ConcurrentHashMap 来实现此目的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-18
    • 1970-01-01
    • 2016-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多