Yuta HIGUCHI | f148aac | 2014-05-05 14:59:06 -0700 | [diff] [blame] | 1 | package net.onrc.onos.core.datastore.utils; |
| 2 | |
| 3 | import net.onrc.onos.core.datastore.DataStoreClient; |
| 4 | |
| 5 | import com.esotericsoftware.kryo.io.Input; |
| 6 | import com.esotericsoftware.kryo.io.Output; |
| 7 | |
| 8 | /** |
| 9 | * {@link Serializer} implementation using Kryo. |
| 10 | */ |
| 11 | public final class KryoSerializer |
| 12 | implements Serializer { |
| 13 | |
| 14 | private final ThreadLocalKryo kryo; |
| 15 | |
| 16 | public KryoSerializer(Class<?>... expectedTypes) { |
| 17 | kryo = new ThreadLocalKryo(expectedTypes); |
| 18 | } |
| 19 | |
| 20 | @Override |
| 21 | public byte[] serialize(Object obj) { |
| 22 | // 1MB RAMCloud limit |
| 23 | Output out = new Output(DataStoreClient.MAX_VALUE_BYTES); |
| 24 | kryo.get().writeClassAndObject(out, obj); |
| 25 | return out.toBytes(); |
| 26 | } |
| 27 | |
| 28 | @Override |
| 29 | public <T> T deserialize(byte[] bytes) { |
| 30 | Input in = new Input(bytes); |
| 31 | @SuppressWarnings("unchecked") |
| 32 | T obj = (T) kryo.get().readClassAndObject(in); |
| 33 | return obj; |
| 34 | } |
| 35 | } |