Sundarrajk's Weblog

PMD – Finalizer Rules

Posted on: September 28, 2011


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();
}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: