I want to allocate an object and make sure that it never is deallocated. Can I tell the garbage collector to ignore an object? No. There isn�t a mechanism for marking an object as undeletable. You can instead create a static member of a class, and store a reference to the object in that. Static members are considered live objects.
I believe if reference to not to be deleted object is declared final then such object can not be derefferenced and hence can not be deleted. The quote asserts that making the reference a static class member, will make it live object. However, in my understanding, it will be live but deletable object. Thanks Barkat [ July 21, 2003: Message edited by: Barkat Mardhani ]
Whether the object is referenced from a final variable or a static variable, it is always possible that the object may be garbage collected. If you have a final variable, the object will remain as long as the variable remains in scope. Take this example:
The object referenced by o is final, but o goes out of scope at the end of the method doIt, so the object is then available for garbage collection. Referencing an object from a static variable doesn't necessarily make the object "immune" from garbage collection, it just makes it more unlikely. Static variables are initialized when the class is loaded and remain so until the class is unloaded (which often doesn't happen until the application terminates). Therefore, if you were to use something like this:
The object o would remain in scope as long as the class Test was loaded. This isn't a fail-safe was of making an object non-collectible, but it's about as good as you can get, I guess. I hope that helps, Corey
Hi Corey, Thanks for taking time to explain. I was thinking of a final reference variable in main() method. The scope of such variable will be life of the execution of application. Thanks Barkat
Joined: Aug 05, 2002
Hi Corey, One more point. If you notice the requirement in quote...".....and make sure......". For that reason I was thinking about a final variable as even static variable are reassignable. Thanks Barkat
Originally posted by Barkat Mardhani: Hi Corey, Thanks for taking time to explain. I was thinking of a final reference variable in main() method. The scope of such variable will be life of the execution of application. Thanks Barkat
In case you have a threaded application then the main thread can complete before the other thread/s.
Joined: Aug 05, 2002
Do we have such thing as Application Object as there is one in VB?
subject: K & B, Ch 7: Garbage Collection, page 439