How will you fix the above memory leak

By providing proper implentation for the key class as shown below with the equals() and hashCode() methods.

 

…..

static class Key {

private String key;

 

public Key(String key) {

this.key = key;

}

 

 

@Override

public boolean equals(Object obj) {

 

if (obj instanceof Key)

return key.equals(((Key) obj).key);

else

return false;

 

}

 

@Override

public int hashCode() {

return key.hashCode();

}

}

…..

If you rerun it after making the fix shown above to the MemoryLeak class, you will get an output as shown below. The program runs endlessly, and creates only one object in the HashMap.

 

map size: 1

Free memory after count 1000 is 4MB

map size: 1

Free memory after count 2000 is 4MB

map size: 1

Free memory after count 3000 is 4MB

map size: 1

Free memory after count 4000 is 4MB

Free memory after count 73000 is 4MB

map size: 1

Free memory after count 74000 is 4MB

map size: 1

Free memory after count 75000 is 4MB