开发者

java static member memory leak

开发者 https://www.devze.com 2023-04-11 00:39 出处:网络
I am reviewing one java code base for finding some memory leaks. During the review I have find the following scenarios.

I am reviewing one java code base for finding some memory leaks. During the review I have find the following scenarios.

  1. A class开发者_开发百科 Class1 has in the codebase. Class1 have some instance variables and some static members. Some other classes creating the instances of the Class1. Is this scenario leads to any memory leak?
  2. A class Class2 available in the codebase. It have some public static inner classes. And the instance of the static inner classes is creating from the other static inner classes. Does it lead to memory leak? For example,
Class2 {
  public static class Class3 {
  }
  public static class Class4 {
  }
  public static class Class3 {
      Class3 c = new Class3();
      //….
  }
  public static int doSomething1{
  }
  public static void doSomething2{
  }
  public void doSomething3{
  }

}

Can somebody give answers?


Creating instances of other classes doesn't in itself create memory leaks.

Holding on to references longer than needed creates memory leaks.

Those references can be explicit or implicit. For example: if you create an instance of a non-static inner class then it will keep a reference to the outer instance, even if no explicit reference to that exists.

So the answer to your direct question is a definite: maybe. You need to give us more information.

And: a pretty good tool to find memory leaks is using a profiler. Especially if it's a big memory leak.


Generally speaking, static members will not be released until you set them to null. Instance variables will be released if the instance itself is unreachable. Static inner classes are just like a normal class and therefore obeys the rule above.

Non-static inner class is as describe by @Joachim Sauer.

p.s. Learn to use a profiler, it'll benefit you for the rest of your programming life :)


I had an issue with memory leak. a colleague recommended a memory profiling tool http://www.eclipse.org/mat/.

I'm no java master, not even close. But what I did was ran my code, monitored for when the program will crash (out of memory), then I would run the code again, but this time, using command line option -Xmx to a number I know would crash the program.

I added too the -XX:+HeapDumpOnOutOfMemoryError, then when the program crash, used the profiling tool and profiled the heap dump.

I was able to find the offending variables/objects. hope that helps, good luck!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号