G
gooch
I am a software engineer who has used C an C++ in the past and I am
currently learning Java. I have been doing some reading and see that
the finalize function of Java operates as the destuctor in C++. I also
have read that the finalize function is not called until garbage
collection occurs. Now you can use the System.gc() call to attempt to
force garbage collection but from everything I have read you are never
guaranteed that garbage collection will occur.
My question then is what do you do if you need to maintain a count of
the number of objects of a class that are instantiated. In C++ I would
normally use a static class variable to hold a count and increment it
on construction and decrement it on destruction. It seems to me that
given what I said in the first paragraph this is not necessarily going
to always give you the correct value. Is there something is paragraph
one that I have misunderstood or would you handle this in some other
way in Java. Thanks.
currently learning Java. I have been doing some reading and see that
the finalize function of Java operates as the destuctor in C++. I also
have read that the finalize function is not called until garbage
collection occurs. Now you can use the System.gc() call to attempt to
force garbage collection but from everything I have read you are never
guaranteed that garbage collection will occur.
My question then is what do you do if you need to maintain a count of
the number of objects of a class that are instantiated. In C++ I would
normally use a static class variable to hold a count and increment it
on construction and decrement it on destruction. It seems to me that
given what I said in the first paragraph this is not necessarily going
to always give you the correct value. Is there something is paragraph
one that I have misunderstood or would you handle this in some other
way in Java. Thanks.