MY mENU


Monday 12 March 2012

Memory and Garbage Collection


Memory and Garbage Collection:

  • As soon as you lose the reference to an object, that object becomes eligible for garbage collection.
  • Setting your object reference to null makes it a candidate for garbage collection.
  • You can directly invoke the garbage collector by getting an object which represents the current runtime and invoking that object’s gc() method.
  • Can’t predict when garbage collection will occur, but it does run whenever memory gets low.
  • If you want to perform some task when your object is about to be garbage collected, you can override the java.lang.Object method called finalize(). This method is declared as protected, does not return a value, and throws a Throwable object, i.e. protected void finalize() throws Throwable.
  • Always invoke the superclass’s finalize() method if you override finalize().
  • The JVM only invokes finalize() once per object. Since this is the case, do not resurrect an object in finalize as when the object is finalized again its finalize() method will not be called. Instead you should create a clone of the object if you must bring the object back to life.
  • Remember that Java passes method parameters by value and not by reference. Obviously then, anything that happens to a primitive data type inside a method does not affect the original value in the calling code. Also, any reassignment of object references inside a method has no effect on the objects passed in.

No comments:

Post a Comment