How can I create a memory leak in Java?

后端 未结 30 1703
没有蜡笔的小新
没有蜡笔的小新 2020-11-21 22:26

I just had an interview, and I was asked to create a memory leak with Java.

Needless to say, I felt pretty dumb having no clue on how to eve

30条回答
  •  囚心锁ツ
    2020-11-21 22:32

    A simple thing to do is to use a HashSet with an incorrect (or non-existent) hashCode() or equals(), and then keep adding "duplicates". Instead of ignoring duplicates as it should, the set will only ever grow and you won't be able to remove them.

    If you want these bad keys/elements to hang around you can use a static field like

    class BadKey {
       // no hashCode or equals();
       public final String key;
       public BadKey(String key) { this.key = key; }
    }
    
    Map map = System.getProperties();
    map.put(new BadKey("key"), "value"); // Memory leak even if your threads die.
    

提交回复
热议问题