Sunday, June 15, 2014

Java Destructor/Deconstructor/finalizer

you cant make memory leaks in Java unless you are holding references to objects - poor programming
or you use a third partyu library from c++ or something

GC cannot always Keep up.

There is no destructor in Java

you can set an object to null and at some point it will get cleaned up by the GeeCee

If you want to clean up somehting use a a method by coding it - eg close();

Rule of them - dont use - some people say use in buggy situation. Code around it,,

Use Finalize() as a backstop to close an external resource.

its on the Java object class - override it

Objects with finalizers (those that have a non-trivial finalize() method) have significant overhead compared to objects without finalizers, and should be used sparingly. Finalizeable objects are both slower to allocate and slower to collect. At allocation time, the JVM must register any finalizeable objects with the garbage collector, and (at least in the HotSpot JVM implementation) finalizeable objects must follow a slower allocation path than most other objects. Similarly, finalizeable objects are slower to collect, too. It takes at least two garbage collection cycles (in the best case) before a finalizeable object can be reclaimed, and the garbage collector has to do extra work to invoke the finalizer. The result is more time spent allocating and collecting objects and more pressure on the garbage collector, because the memory used by unreachable finalizeable objects is retained longer. Combine that with the fact that finalizers are not guaranteed to run in any predictable timeframe, or even at all, and you can see that there are relatively few situations for which finalization is the right tool to use.

No comments:

Post a Comment