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