Reputation: 44042
Is it possible to tell Ehcache to use a custom serialization when moving an object from the memory to the disc or off-heap cache and the other way? I want to skip some fields from serialization which are not declared transient (third-party-library) but which I do not need to store since I can easily recalculate them. I want to do this to save quite some memory. At best, I want to use a library like Kryo.
Upvotes: 1
Views: 3632
Reputation: 44042
I found a solution by using wrappers and by adding another abstraction layer, a SerializationWrapper
. The wrapper presented here uses Kryo:
final class SerializationWrapper implements Serializable {
private final static Kryo KRYO = new Kryo();
private Object object;
public SerializationWrapper(Object object) {
this.object = object;
}
private void readObject(ObjectInputStream objectInputStream)
throws IOException, ClassNotFoundException {
Input input = new Input(objectInputStream);
object = KRYO.readClassAndObject(input);
input.close();
}
private void writeObject(ObjectOutputStream objectOutputStream)
throws IOException {
Output output = new Output(objectOutputStream);
KRYO.writeClassAndObject(output, object);
output.close();
}
public Object getWrappedObject() {
return object;
}
}
The serialization methods readObject
and writeObject
will be called by the Java contract and allow me to implement a custom serialization. Additionally, This solution does not create a size overhead since I only write the wrapped object to the output stream and skip the writing of the wrapper entirely. You can also read this documentation for more info what helped me a lot.
Upvotes: 3