blob: 26d4fd19ca83c6e3cbd59b32a5eb7f1b9f194a16 [file] [log] [blame]
Yuta HIGUCHIf148aac2014-05-05 14:59:06 -07001package net.onrc.onos.core.datastore.utils;
2
Yuta HIGUCHI7e5bfbe2014-08-02 16:37:02 -07003import javax.annotation.concurrent.ThreadSafe;
4
Yuta HIGUCHIf148aac2014-05-05 14:59:06 -07005import net.onrc.onos.core.datastore.DataStoreClient;
6
7import com.esotericsoftware.kryo.io.Input;
8import com.esotericsoftware.kryo.io.Output;
9
10/**
11 * {@link Serializer} implementation using Kryo.
12 */
Yuta HIGUCHI7e5bfbe2014-08-02 16:37:02 -070013@ThreadSafe
Yuta HIGUCHIf148aac2014-05-05 14:59:06 -070014public final class KryoSerializer
15 implements Serializer {
16
17 private final ThreadLocalKryo kryo;
18
Yuta HIGUCHI7e5bfbe2014-08-02 16:37:02 -070019 /**
20 * Thread safe Serializer implementation using Kryo.
21 *
22 * @param expectedTypes list of classes expected to be serialized
23 */
Yuta HIGUCHIf148aac2014-05-05 14:59:06 -070024 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}