Implementing java.io.Externalizable for Maximum Cache Performance

As a part of its normal operation, Cacheonix sends keys and cached values (further cache objects) across the network. To be able to do so, Cacheonix requires the cache objects to be serializable. Serialization is a process of converting an object to a byte stream that can be sent across the network and that can be used to reconstruct the object on a receiving side.

Default Java Serialization Is Very Inefficient

The simplest way to make an object serializable in Java is to have an object class implement a signature interface java.io.Serializable. A signature interface is an interface that doesn't declare any methods, so the class declaring it doesn't actually have to implement any methods. Declaring java.io.Serializable just signals that it is OK to send the object over the network. Cacheonix will use default Java serialization to serialize classes declaring java.io.Serializable. Unfortunately, in most cases, the default Java serialization is too slow, and the resulting byte output is too big to be used efficiently to serialize cache objects.

Implementing java.io.Externalizable for Serialization Is The Best Option

Implementing java.io.Externalizable allows to maximize cache performance by reducing the serialization overhead to minimum. This is the fastest way compared to any serialization framework. A class implementing java.io.Externalizable must provide three things:

  1. A default (no-argument) public constructor
  2. A method named writeObject()
  3. A method named readObject()

Method writeObject() must write object fields to an ObjectOutput. Here is an example of an implementation of writeObject():

public void writeExternal(final ObjectOutput out) throws IOException {

      out.writeObject(invoiceDate);
      out.writeInt(invoiceID);
      out.writeInt(invoiceNumber);
      out.writeInt(customerID);
   }

Method readObject() must read object fields from an ObjectInput in the same order they were written in writeObject(). Here is an example of an implementation of readObject():

public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {

      invoiceDate = (Date) in.readObject();
      invoiceID = in.readInt();
      invoiceNumber = in.readInt();
      customerID = in.readInt();
   }

Here is a complete example of a class implementing java.io.Externalizable{{}}.

Testing Cache Keys and Values for Serializability

Implementing java.io.Externalizable has a drawback: it requires code, and code means bugs. Failure to serialize and deserialize a cache object properly may cause serious production problems. That's why it is critical to test all your keys and values for serializability. A separate technical note tells you how to test cache objects for serializability.

 

Labels

 
(None)