Objects, garbage collection and Threads question

Maximilian

Lifer
Feb 8, 2004
12,604
15
81
Just to clarify if i run this it creates 20 objects and 19 of them are garbage collected because only the final one has a reference yeah?

Code:
for (int count = 0; count <20; count ++)
{
	MyObject jerry = new MyObject();
}

If that's true then are Thread objects special in some way? What prevents a Thread from being garbage collected when it has no reference?
 

Maximilian

Lifer
Feb 8, 2004
12,604
15
81
Aha yeah i suppose there must be a reference somewhere, that probably how the Thread.currentThread() method works.
 

BrightCandle

Diamond Member
Mar 15, 2007
4,762
0
76
Threads are the root of garbage collection, they count as the places where things can be referenced from. Your basic GC algorithm iterates the threads, and in each goes through any references on the stack frame and marks all the objects found. Then you go through any static values and mark those. Everything else is junk.

So threads are different because they are a first class root in the garbage collector.