Usage of Hashmap as thread safe in parallel test execution

Viewed 378

I have a class used to generate random values and put these random values into a hashmap. But I have configured the test suite to be able to execute paralley. So, I have declared constroctor as private to be thread-safes this hashmap. Is this mechanism right?. If it is incorrect, how can I achieve it?

public  class RandomData{
    private static Hashmap map = new Hashmap();

    private RandomData(){}

    public String getRandomVal(){

        /* generate random value and put the map, if this generated 
         value is not existing in the map, it will return or else 
         a new value is generated again and return. */
    }
}
3 Answers

You have a single instance of a HashMap, that is shared between all the instances of RandomData. If multiple threads try to update it (by calling getRandomVal) concurrently, you may get undefined behavior, since HashMap is not thread-safe. You could solve this by using a thread-safe implementation of Map, such as ConcurrentHashMap.

HashMaps are not thread safe. Making a variable/method does not make it thread-safe.You should use ConcurrentHashMaps or HashTable for thread safety.

No just making constructor private doesn't make class thread safe

 public static class RandomData {
        private static final ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

        private RandomData() { }

        public String getRandomVal() {

        /* generate random value and put the map, if this generated
         value is not existing in the map, it will return or else
         a new value is generated again and return. */

        }


    }

Use ConcurrentHashMap and its methods:

look at:

ConcurrentHashMap::computeIfAbsent
ConcurrentHashMap::putIfAbsent

these methods are atomic and guaranteed to be safe.

Related