Using the IMDG’s NamedMap/NamedCache with Writables

By default, it is assumed that the objects stored in the named map or the named cache are serialized and deserialized using the standard Java serialization framework. To use other serialization frameworks, a custom serializer must be provided to each instance of the ScaleOut StateServer named cache. ScaleOut hServer includes a custom serializer of type WritableSerializer for Hadoop Writable types, so that these objects can be conveniently stored and retrieved from the IMDG. The WritableSerializer takes the Writable-implementing type of objects it serializes and deserializes as a constructor parameter. To assign a custom serializer to the named map, use the factory method which takes custom serializers for key and value:

NamedMap<Text, IntWritable> map = NamedMapFactory.getMap("myMapW",
                new WritableSerializer<Text>(Text.class),
                new WritableSerializer<IntWritable>(IntWritable.class));
map.put(new Text("myText"), new IntWritable(1));

To install a custom serializer for a named cache, it should be passed to the named cache instance by calling setCustomSerialization(…):

// Construct the named cache and set custom serialization
NamedCache cache = CacheFactory.getCache("cache");
cache.setCustomSerialization(
new WritableSerializer(LongWritable.class));

// Put some numbers in the named cache as objects:
LongWritable number = new LongWritable();
for (long i = 0; i < NUMBER_OF_OBJECTS; i++) {
    number.set(i);
    cache.put("" + i, number);
}

// Retrieve them back:
for (long i = 0; i < NUMBER_OF_OBJECTS; i++) {
    number = ((LongWritable) cache.get("" + i));
    if (i != number.get()) System.out.println("Objects do not match.");
}