0

In Java, can a java.util.HashMap<Key, Value> overflow silently, so content is deleted without me receiving an exception or some other notification? If yes, how do I make it noticeable?

I meant can it exceed the physical hardware memory, not the reserved memory for the HashMap object.

Phil
  • 7,065
  • 8
  • 49
  • 91
  • This doesnt make sense. `HashMap`s dynamically grow in size, and have no limit. Every value has a specific key, and unless you remove it yourself, it'll stay there (unless you're using a `WeakHashMap`, in which things will be removed from the map if the only reference to that item is the map) – Vince Oct 30 '14 at 16:28

3 Answers3

3

No, HashMaps do not evict elements automatically. If the buckets get too full, the buckets are expanded and all the elements are rehashed automatically.

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
  • I meant can if it exceeds the physical hardware memory, not the reserved memory for the hashmap-object. – Phil Oct 30 '14 at 16:31
  • 2
    @DBRN Then you will receive an `OutOfMemoryError`, and life will suck for you. But your `HashMap` still won't lose elements. Also, before getting to this point, your GC will be running at 100% continuously trying to free up memory, and your program will be very slow.... – C. K. Young Oct 30 '14 at 16:32
  • So there is no way an OutOfMemoryError would be not thrown or be invisible? – Phil Oct 30 '14 at 16:34
  • 2
    An `OutOfMemoryError` will indeed be thrown. In theory, code can catch it, but catching `Error`s of any type is bad practice, so don't do it. – C. K. Young Oct 30 '14 at 16:35
3

From the docs

When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets

A HashMap will never "overflow", it will simply resize. This will repeatedly happen until you run out of memory, which will cause a very loud error.

Floegipoky
  • 3,087
  • 1
  • 31
  • 47
2

Other answers are correct but there is one weird edge-case. See Theoretical limit for number of keys (objects) that can be stored in a HashMap? and the discussion about what happens when there are more entries in the Map than Integer.MAX_VALUE.

As such it would be theoretically possible - if you somehow managed to break that limit (which is close to impossible) and the JVM survived handling that many objects (which is close to impossible) and your program survived that limit (which is close to impossible) then not only would objects begin to seem to disappear from your Map but you would be half way to earning yourself a breakfast at Milliways where If you've done six impossible things this morning, why not round it off with breakfast at Milliways, the Restaurant at the End of the Universe.

Community
  • 1
  • 1
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213