Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WeakHashMap and Concurrent Modification

I'm reading the Java Doc about the WeakHashMap and I get the basic concept. Because of the GC thread(s) acting in the background, you can get 'unusual behavior', such as a ConcurrentModificationException when iterating and etc.

The thing I don't get is that if the default implementation is not synchronized and does not contain lock in any way, then how come there is no possibility of getting an inconsistent state. Say you have 2 threads. A GC thread deleting some key at a certain index and at same time and at the same index, a user thread is inserting in the array a key value pair.

To me, if there is no synchronization, then there is a high risk of getting a hash map that is inconsistent.

Even worse, doing something like this might actually be super dangerous because v might actually be null.

if (map.contains(k)) {
   V v = map.get(k)
}

Am I missing something?

like image 584
jeremie Avatar asked Jul 02 '26 00:07

jeremie


1 Answers

The inconsistent state issues you mention do not arise because the GC does not actively restructure WeakHashMaps. When the garbage collector frees the referent of a weak reference, the corresponding entry is not physically removed from the map; the entry merely becomes stale, with no key. At some later point, the entry may be physically removed during some other operation on the map, but the GC won't take on that responsibility.

You can see one Java version's implementation of this design on grepcode.

like image 52
user2357112 supports Monica Avatar answered Jul 03 '26 12:07

user2357112 supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!