Bastien
Bastien

Reputation: 1597

Thread safety for synchronized HashMap's clear() method

I have a HashMap consisting of unique int keys (autoboxing to Integer) and double[] values. Size is ~100. I'm only using .put() & .get() methods. I need to regularly "reset" the HashMap and repopulate it with new key/values pairs. I do that using a .clear(), and .put() in a loop to repopulate (I could also simply create a new HashMap instead).

In a single-threaded environment, no issue at all.

In a multi-threaded environment, I can use a SynchronizedMap, or a ConcurrentHashMap, both will take care of my put() & get() thread safety.

What about the .clear() method ? How to ensure it's thread-safe ? Should I simply use a synchronized block ?

Also, how would creating a new HashMap instead have an impact on thread safety in this context ?

Upvotes: 2

Views: 978

Answers (1)

Suresh Atta
Suresh Atta

Reputation: 122008

The clear method have the locking management as well.

  void  clear() {
577             if (count != 0) {
578                 lock();
579                 try {
580                     HashEntry<K,V>[] tab = table;
581                     for (int i = 0; i < tab.length ; i++)
582                         tab[i] = null;
583                     ++modCount;
584                     count = 0; // write-volatile
585                 } finally {
586                     unlock();
587                 }
588             }
589         }
590     }

Upvotes: 3

Related Questions