Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

About Creating a Memory Leak in a Java Program  RSS feed

 
Ravi Kiran Va
Ranch Hand
Posts: 2234
Eclipse IDE Firefox Browser Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I have went through this from a site .

Java memory Leaks can occur in the following ways:

Saving an Object reference in to class level collection and forgetting to remove it at the proper time.

So for this i have written like this




Is this correct ??
 
Campbell Ritchie
Marshal
Posts: 55687
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can see two potential errors: you haven't indented it correctly and you are not adding multiple references. You are adding one static reference many times. Anyway, your List and all its contents will go out of scope and vanish when that method completes.

Find a copy of Bloch's Effective Java, where there is a better example with a Stack. Can't remember the page and I haven't got my copy to hand at the moment.
 
Rob Spoor
Sheriff
Posts: 21089
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's the short version of the Stack without any error / range checking:
Consider you push 10 objects. The array is then filled. You then pop the 10 objects again. The index is decreased, but the array still holds references to the objects. The solution is to null out references that would otherwise remain (especially in arrays but also in collections) to elements you no longer need:

Another simple example is one that looks like the original example:
No matter what happens, instances of this class will never be garbage collected anymore because the static List still has references to them. Every new instance will only increase the amount of memory used.
 
Ulrika Tingle
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ravi Kiran V wrote:Saving an Object reference in to class level collection and forgetting to remove it at the proper time.


That's not a memory leak. It's called involuntary object retention. It means you cling on to objects you thought were eligible for garbage collection but they aren't.

If you fill a static ArrayList with objects they will stay there until the program ends (unless you remove them). That's expected behaviour. If anything is leaking it's rather programmer's memory.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!