Yogesh Gandhi wrote:
What I know is that if there is no reference that is pointing to a memory, then garbage collector will re-collect the memory according to java norms and documentation.
A more correct way to think about it is ... if an object is not reachable from a root, then the garbage collector will collect the memory (it may get a bit more complex with weak references, and what happens during the finalizer process, but let's simply ignore those).
Thinking about it as reachable is better because it is possible for an object to have a reference pointing to it, but it is not reachable -- in the case where the object is being referred to by an object that itself is not reachable. Also, thinking in terms of roots is also important, as there are many roots. The stacks of all running threads are roots (including those that hasn't been cleaned up yet). This includes your main thread, threads internal to the JVM, and any threads that you start. Class definitions can be considered as roots (especially since the default class loader won't unload classes for applications). This is because static variables can reach objects. And of course, the JVM has lots of internal data structures that may reach objects.
Yogesh Gandhi wrote:
But, I got confused when I saw the following scenario. Will garbage collection happen in this case as well?
In this case, a never ending thread is created, and started.
Well. I don't need to run it to tell you that you will get an out of memory condition -- most likely running out of stack space needed to create the threads. You can create a ridiculous amount of threads in 10 seconds, so will need a ridiculous amount of memory to survive such a request.
Yogesh Gandhi wrote:
As far as my knowledge is concerned, reference to thread created and should be destroyed as soon as it encounters closing bracket of while.
Remember.... reachable from roots. The started threads can reach there own thread object.
Yogesh Gandhi wrote:
But if it'll release the memory, how the thread will continue to run?
If it'll not release the memory, then is this a case of memory leakage???
Henry