Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This noncompliant code example defines the ExceptionReporter interface that is implemented by the class ExceptionReporters. This class is useful for reporting exceptions after filtering out any sensitive information (EXC05-J. Use a class dedicated to reporting exceptions). The constructor of ExceptionReporters, incorrectly publishes the this reference before construction of the object has concluded. This is because it sets the exception reporter in the constructor (statement er.setExceptionReporter(this)). It is misleading that, because it is the last statement in the constructor, it must be benign.

Consider the The class MyExceptionReporter, that subclasses ExceptionReporters with the intent of adding a logging mechanism that logs critical messages before an exception is reported. Its constructor invokes the superclass's constructor (a mandatory first step) which publishes the exception reporter, before the initialization of the subclass has concluded. Note that the subclass initialization consists of obtaining an instance of the default logger.

...

In this noncompliant code example, the constructor for class BadExceptionReporter uses an anonymous inner class to publish a filter() method. The problem surfaces occurs because the this reference of the outer class is published by the inner class so that other threads can see it. If the class is subclassed, the issue described in the first noncompliant code example resurfaces.

...

Wiki Markup
A {{private}} constructor alongside a {{public}} factory method may be used when it is desirabledesired to publish the {{filter()}} method from within the constructor. \[[Goetz 06|AA. Java References#Goetz 06]\]

...