How can I create a memory leak in Java?

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

    I thought it was interesting that no one used the internal class examples. If you have an internal class; it inherently maintains a reference to the containing class. Of course it is not technically a memory leak because Java WILL eventually clean it up; but this can cause classes to hang around longer than anticipated.

    public class Example1 {
      public Example2 getNewExample2() {
        return this.new Example2();
      }
      public class Example2 {
        public Example2() {}
      }
    }
    

    Now if you call Example1 and get an Example2 discarding Example1, you will inherently still have a link to an Example1 object.

    public class Referencer {
      public static Example2 GetAnExample2() {
        Example1 ex = new Example1();
        return ex.getNewExample2();
      }
    
      public static void main(String[] args) {
        Example2 ex = Referencer.GetAnExample2();
        // As long as ex is reachable; Example1 will always remain in memory.
      }
    }
    

    I've also heard a rumor that if you have a variable that exists for longer than a specific amount of time; Java assumes that it will always exist and will actually never try to clean it up if cannot be reached in code anymore. But that is completely unverified.

提交回复
热议问题