【发布时间】: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