Step 9: A custom externalizer

When we introduced clustering to our application, we pointed out the need for keys and values to be serializable. Infinispan, however, doesn't use standard Java serialization but a much higher performance library called JBoss Marshalling. Usually you don't need to do anything else to your entities, aside implementing since JBoss Marshalling takes care of everything for you. There are cases, however, where you might want to have full control over the serialization format, for example to support backwards and forwards compatibility of entities which might change during the lifetime of a project. In this case you need to provide a custom Externalizer. An Externalizer is simply a class which knows how to read and write your entities over a stream. Let's write a simple externalizer for our LocationWeather class:

public static class LWExternalizer implements Externalizer<LocationWeather> {
  public void writeObject(ObjectOutput output, LocationWeather object) throws IOException {
  public LocationWeather readObject(ObjectInput input) throws IOException, ClassNotFoundException { 
    float temperature = input.readFloat();
    String conditions = input.readUTF();
    String country = input.readUTF();
    return new LocationWeather(temperature, conditions, country);
We also need to add a special annotation to our entity, declaring the externalizer that should be used for it:
public class LocationWeather implements Serializable {
That's it. Since we didn't do anything special, running the application won't show any visible differences, but now you have a better idea about what's happening under the hood.
$ git checkout -f step-9
$ mvn clean package exec:exec # on terminal 1
$ mvn exec:exec # on terminal 2

Now we are ready to tackle something a bit more interesting: we will use Infinispan to do something with the data, instead of just storing and retrieving it.

back to top