This is an example of Java source code, that leads to a memory waste and few potential problems.

The doSomeWork() method in the following class may be called repeatedly by some client that uses the Example class. The tmp variable , used only within doSomeWork(), has been placed as field of the class, in an attempt to save memory.
But the actual effect is quite the opposite.

public class Example {

  /** Used only in {#doSomeWork()}. */
  private CustomClass tmp;

  /**
   * Called by some client.
   */
  public void doSomeWork() {
    tmp = new CustomClass();
    // some stuff...
  }

  // other methods...

}

Regardless the CustomClass implementation (it may be a class of ours or of a library), the object referenced by tmp remains allocated for the Example instance’s whole lifecycle, unless tmp is assigned to null when not needed anymore (but why one would do the virtual machine’s job).

Moreover this way ha a big collateral effect: Example instances are thread-unsafe, because tmp becomes a state variable and could be simultaneously accessed by multiple threads calling doSomeWork().

On second thought, the separation of concern internal to Example class is violated, because tmp could be used by other class’s methods (this is a flaw that could lead to serious bugs).

The following solution is surely better:

public class Example {

  /**
   * Called by some client.
   */
  public void doSomeWork() {
    final CustomClass tmp = new CustomClass();
    // some stuff...
  }

  // other methods...

}

Now the tmp’s scope is limited to the method it is used in, the Example class is thread-safe and the CustomClass lifecycle is shortened (CustomClass instances could be garbage-collected at method’s end or even before).
As a final note, the fact that now the variable could be declared final represents an added value.

Annunci