开发者

Pointers, links, object and reference count

String a = "a"; // allocate memory and write address of a memory block to a variable
String b = "b";

// a and b hold addresses

b = a; // copy a address into b. 

// Now what? b value is completely lost and will be garbage collected

//*** next step


a = null; // now a does not hold a valid address to any data, 

// still data of a object exist somewhere, yet we cannot get access to it.

Correct me if there's a mistake somewhere in my reflexions.

My question is:

suppose anInstance object of type Instance has a property ' surname 开发者_C百科' anInstance.getSurname() returns "MySurname".

now String s = anInstance.getSurname();
anInstance = null;

question is - is it true that getSurname value, namely MySurname will not be garbage collected because and only because it has active reference counter > 0, and if other properties of anInstance have a zero reference counter, they'll be garbage collected?


MySurname will not be garbage collected because it has an active reference, s, but there is no reference count as such. Java's garbage collector doesn't rely on reference counting.


Java uses a garbage collection algorithm that's much more sophisticated than a simple reference count.

Yes, it's possible for anInstance and any objects it references to be GC'd, which surname is not. Whether or not this happens depends on scope and other factors that you don't describe. I don't think your question gives enough context to allow a meaningful answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜