Wednesday, September 28, 2011

PMD - Finalizer Rules

The Seventh installment of explanation of PMD checks covering Finalizer Rules.

Finalizer Rules

These rules deal with different problems that can occur with finalizers. Finalizer methods are to be used to clean up any resource that needs to be cleaned up when the object is Garbage Collected.

EmptyFinalizer

If the finalize() method is empty, then it does not need to exist.

Example

public class Foo {
   protected void finalize() {}
}

FinalizeOnlyCallsSuperFinalize

If the finalize() is implemented, it should do something besides just calling super.finalize().

Example

public class Foo {
   protected void finalize() {
     super.finalize();
   }
}

FinalizeOverloaded

Methods named finalize() should not have parameters. It is confusing and probably a bug to overload finalize(). It will not be called by the VM.

Example

public class Foo {
   // this is confusing and probably a bug
   protected void finalize(int a) {
   }
}

FinalizeDoesNotCallSuperFinalize

If the finalize() is implemented, its last action should be to call super.finalize.

Example

public class Foo {
   protected void finalize() {
       something();
       // neglected to call super.finalize()
   }
}

FinalizeShouldBeProtected

If you override finalize(), make it protected. If you make it public, other classes may call it.

Example

public class Foo {
public void finalize() {
  // do something
}
}

AvoidCallingFinalize

Object.finalize() is called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

Example

public class Foo {
void foo() {
  Bar b = new Bar();
  b.finalize();
}
}

No comments: