Home > Back-end >  ConcurrentHashMap - do we synchronize methods which access the map
ConcurrentHashMap - do we synchronize methods which access the map

Time:08-01

I am new to java and Multithreading.

I have created the below class where I am using ConcurrentHashMap. I understand that ConcurrentHashMap is thread safe. But what about the startTime and endTime methods.

Do I need to synchronize the startTime and endTime APIs?

class ProfileStatistics
{
    private static final ProfileStatistics s_instance = new ProfileStatistics();
    Map<Long, Long> mp                                = new ConcurrentHashMap<>();
    static ProfileStatistics getInstance()
    {
        return s_instance;
    }

    synchronized void startTime() throws InterruptedException
    {
        mp.put(Thread.currentThread().getId(), System.currentTimeMillis());
    }

    synchronized long endTime()
    {
        long tId       = Thread.currentThread().getId();
     
        if(mp.containsKey(tId))
        {
            long start = mp.get(tId);
            mp.remove(tId);
         
            return System.currentTimeMillis() - start;
        }
        return 0L;
    }
}

CodePudding user response:

As you are using the thread id as the key to the Map, you do not need to synchronise these methods, because two threads will never try to use the same key. You do need to use a ConcurrentHashMap, because two threads modifying a HashMap or other non thread safe Map concurrently is not safe.

If it was possible for two threads to have the same id, you would need to think about endTime.

For the sake of argument, imagine that two threads (thread1 and thread2), both having the same id, call endTime simultaneously.

Both threads can call mp.containsKey(tId) and see a return value of true.

Then one thread might get and remove the value.

Then the second thread will get a NullPointerException when it tries to unbox the result of get.

  • Related