In which cases will a hashmap in java lose some entries?

Here are some things that may cause entries to be "lost":

  • Incorrectly implemented equals / hashcode methods on your key objects. These two methods need to conform to a "contract" for the hash table to work properly. The most important property is:

    key1.equals(key2) IMPLIES key1.hashcode() == key2.hashcode
    
  • Mutable key objects that are changed while the key is used in the map. In particular, if the key change cause the key's hashcode to change, it will be lost. (In this case, the entries will show up if you iterate over the entire map. But the map operations that use has lookup won't find them ... because they are on the wrong hash chain.)

    The safest approach is to use a key class that is immutable.

  • Use of a map in a multi-threaded application without proper synchronization. This can cause corruption of the map data structure which could manifest as lost entries.

  • Some other part of your application that you are not aware of is removing the entries.


The answers that state/stated that you have to override equals and hashcode are/were incorrect. There are situations where the Object implementations of these methods are exactly what is required. What you have to do is make sure that:

  1. you are using an appropriate form of key equality as required by your use-case, and
  2. your equals and hashcode conform to "the contract".

What can I do to troubleshoot this?

I'd recommend a code inspection to check the above issues.

Debugging is another alternative. For instance, you could look to see if you can find the missing entries on the wrong hash chain. However, I suspect that approach could be a bit "hit and miss".

I am using weblogic as server.

Not relevant ... unless you happen to be using some Map implementation class that is implemented by Weblogic rather than J2SE. (Look at the object's classname.)

Should I play with any environment value?

No. It won't help


One possible scenario is:

If key is instance of class and that class didn't override equals/hashcode methods, then get method may return false.


If your Keys are mutable, then mutating the Key in a way which changes its hashvalue will cause the lookup to fail.

For example, assume you have the following mutable class:

public class MyKey {
    private int value;
    public void setValue(int value) {
        this.value = value;
    }
    public int hashCode() {
        return value;
    }
    public boolean equals(Object obj) {
        //...
    }
}

Then this is possible:

MyKey key = new MyKey();
key.setValue(1);

Map<MyKey, String> map = new HashMap<MyKey, String>();
map.put(key, "Hello");

System.out.println("map contains: " + map.get(key)); // "map contains: Hello"
key.setValue(2);
System.out.println("map contains: " + map.get(key)); // "map contains: "