How can I create a memory leak in Java?

后端 未结 30 1736
没有蜡笔的小新
没有蜡笔的小新 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:43

    What's a memory leak:

    • It's caused by a bug or bad design.
    • It's a waste of memory.
    • It gets worse over time.
    • The garbage collector cannot clean it.

    Typical example:

    A cache of objects is a good starting point to mess things up.

    private static final Map myCache = new HashMap<>();
    
    public void getInfo(String key)
    {
        // uses cache
        Info info = myCache.get(key);
        if (info != null) return info;
    
        // if it's not in cache, then fetch it from the database
        info = Database.fetch(key);
        if (info == null) return null;
    
        // and store it in the cache
        myCache.put(key, info);
        return info;
    }
    

    Your cache grows and grows. And pretty soon the entire database gets sucked into memory. A better design uses an LRUMap (Only keeps recently used objects in cache).

    Sure, you can make things a lot more complicated:

    • using ThreadLocal constructions.
    • adding more complex reference trees.
    • or leaks caused by 3rd party libraries.

    What often happens:

    If this Info object has references to other objects, which again have references to other objects. In a way you could also consider this to be some kind of memory leak, (caused by bad design).

提交回复
热议问题