• Post Reply Bookmark Topic Watch Topic
  • New Topic

Will reference to the same type create a memory leak?  RSS feed

 
Emil Iakoupov
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In a class i have reference to the same type, here is the example.



Will instantiating Example create a memory leak (consumption) - infinite creation of Example objects? Very simple example.
 
Paul Clapham
Sheriff
Posts: 22835
43
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If creating an Example object unconditionally causes another Example object to be created, then yes, that will cause an infinite number of Example objects to be created. Of course that can't happen in real life so your program will crash. However you are more likely to use up all of your stack space in recursive calls before you run out of memory.

In your example, that is the case. Creating an Example does unconditionally cause another Example object to be created.

And no, that isn't a "memory leak". That term refers to the case where you lose track of some memory, so that garbage collection is unable to deal with it and it just stays in memory taking up space. It is impossible to do that in current versions of Java, since the garbage-collection algorithms have been so well debugged over the last decade or so. Or at least if it's possible, the ways you can do it are extremely hard to find (and you won't find them).
 
Praveen Kumar M K
Ranch Hand
Posts: 256
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have a question on this.



I tried the code given by Emil as well as the constructor above. In either case as indicated I got a StackOverflowError error. Why do we always get this error and not the OutOfMemoryError? I mean, both, the number of references and the number of instances have to increase proportionally. Is it because Stack memory is less than main memory?
 
Paul Clapham
Sheriff
Posts: 22835
43
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Short answer: yes. The number of recursive calls you can put into your stack is much smaller than the number of Example objects you can create in your available memory.
 
Praveen Kumar M K
Ranch Hand
Posts: 256
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply Paul!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!