Kim Nedergaard Clausen
Kim Nedergaard Clausen

Reputation: 232

One HashMap, two threads - how do I ensure thread-safety in this example?

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.

Upvotes: 0

Views: 172

Answers (1)

NyxCode
NyxCode

Reputation: 728

Is it possible that the get() method will attempt to copy testHashMap while it's being written to by TestThread?

No. The get() method just returns the map. No copying going on here.

But yes, you have to somehow control the access to the map since HashMap is not threadsafe. You can achieve this by synchronizing a hashmap (Map<A, B> map = Collections.synchronizedMap(new HashMap<A, B>());) or using a ConcurrentHashMap.

Upvotes: 1

Related Questions