How can I create a memory leak in Java?

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

    Static field holding object reference [esp final field]

    class MemorableClass {
        static final ArrayList list = new ArrayList(100);
    }
    

    Calling String.intern() on lengthy String

    String str=readString(); // read lengthy string any source db,textbox/jsp etc..
    // This will place the string in memory pool from which you can't remove
    str.intern();
    

    (Unclosed) open streams ( file , network etc... )

    try {
        BufferedReader br = new BufferedReader(new FileReader(inputFile));
        ...
        ...
    } catch (Exception e) {
        e.printStacktrace();
    }
    

    Unclosed connections

    try {
        Connection conn = ConnectionFactory.getConnection();
        ...
        ...
    } catch (Exception e) {
        e.printStacktrace();
    }
    

    Areas that are unreachable from JVM's garbage collector, such as memory allocated through native methods

    In web applications, some objects are stored in application scope until the application is explicitly stopped or removed.

    getServletContext().setAttribute("SOME_MAP", map);
    

    Incorrect or inappropriate JVM options, such as the noclassgc option on IBM JDK that prevents unused class garbage collection

    See IBM jdk settings.

提交回复
热议问题