I have a question about thread-safety and HashMaps. More specifically, I'm wondering if there's a chance that one thread tries to read from a HashMap while it's being written to. Here's a rough example:
I have a class called "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();
}
}
}
And I have another class called 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;
}
}
Is it possible that the get() method will attempt to copy testHashMap while it's being written to by TestThread? And if so, how do I ensure thread-safety in this example? Do I have to create a synchronizedMap instead of a HashMap?
Thanks in advance.