Forums Register Login

Will reference to the same type create a memory leak?

+Pie Number of slices to send: Send
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.
1
+Pie Number of slices to send: Send
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).
+Pie Number of slices to send: Send
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?
1
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
Thanks for the reply Paul!
Think of how stupid the average person is. And how half of them are stupider than that. But who reads this tiny ad?
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 643 times.
Similar Threads
Memory Leak?
Reference variable
Does Java have buffer overflows and memory leaks?
Memory Leaks - Where and How
What do you mean by memory leak in Java?
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 12:49:19.