Caching

To illustrate caching, I extend the server object used in the previous sections. I add three accessor methods to access the three server instance variables:

public boolean getBoolean( );
public int getNumber( );
public String getString ( );

Now you can add a generic server-object proxy implementation that handles caching. The implementation is essentially the same for all three communication layers:

package tuning.distrib.custom;

public class ServerObjectCacher
  implements ServerObject
{
  ServerObject stub;
  boolean b;
  boolean bInit;
  int i;
  boolean iInit;
  String s;
  boolean sInit;

  public ServerObjectCacher(ServerObject stub)
  {
    super ( );
    this.stub = stub;
  }

  public boolean getBoolean( )
  {
    if (bInit)
      return b;
    else
    {
      b = stub.getBoolean( );
      bInit = true;
      return b;
    }
  }

  public int getNumber( )
  {
    if (iInit)
      return i;
    else
    {
      i = stub.getNumber( );
      iInit = true;
      return i;
    }
  }

  public String getString ( )
  {
    if (sInit)
      return s;
    else
    {
      s = stub.getString( );
      sInit = true;
      return s;
    }
  }

  public void setBoolean(boolean flag)
  {
    bInit = false;
    stub.setBoolean(flag);
  }

  public void setNumber (int i)
  {
    iInit = false;
    stub.setNumber(i);
  }

  public void setString(String obj)
  {
    sInit = false;
    stub.setString(obj);
  }

  public void setAll(boolean flag, int i, String obj)
  {
    bInit = iInit = sInit = false;
    stub.setAll(flag, i, obj);
  }
}

As you can see, this is a simple proxy object. Each accessor is lazily initialized, and calling any updating method resets the accessors so that they need to be reinitialized ...

Get Java Performance Tuning now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.