blob: 19517f3c4a215604789a63b10d7f2e353cb9f41b [file] [log] [blame]
Yuta HIGUCHIad4c2182014-09-29 11:16:23 -07001package org.onlab.onos.store.serializers;
2
Yuta HIGUCHIad4c2182014-09-29 11:16:23 -07003import org.onlab.util.KryoPool;
4import org.slf4j.Logger;
5import org.slf4j.LoggerFactory;
6
tomf5d85d42014-10-02 05:27:56 -07007import java.nio.ByteBuffer;
Yuta HIGUCHIad4c2182014-09-29 11:16:23 -07008
9/**
Yuta HIGUCHI672488d2014-10-07 09:23:43 -070010 * Serializer implementation using Kryo.
Yuta HIGUCHIad4c2182014-09-29 11:16:23 -070011 */
Yuta HIGUCHI672488d2014-10-07 09:23:43 -070012public class KryoSerializer implements Serializer {
Yuta HIGUCHIad4c2182014-09-29 11:16:23 -070013
14 private final Logger log = LoggerFactory.getLogger(getClass());
15 private KryoPool serializerPool;
16
17
Yuta HIGUCHI672488d2014-10-07 09:23:43 -070018 public KryoSerializer() {
Yuta HIGUCHIad4c2182014-09-29 11:16:23 -070019 setupKryoPool();
Yuta HIGUCHIad4c2182014-09-29 11:16:23 -070020 }
21
22 /**
23 * Sets up the common serialzers pool.
24 */
25 protected void setupKryoPool() {
Yuta HIGUCHIad4c2182014-09-29 11:16:23 -070026 serializerPool = KryoPool.newBuilder()
Yuta HIGUCHI03fec1f2014-10-03 09:13:50 -070027 .register(KryoPoolUtil.API)
Yuta HIGUCHIad4c2182014-09-29 11:16:23 -070028 .build()
29 .populate(1);
30 }
31
32 @Override
Yuta HIGUCHI53a285d2014-10-06 23:58:01 -070033 public byte[] encode(final Object obj) {
Yuta HIGUCHIad4c2182014-09-29 11:16:23 -070034 return serializerPool.serialize(obj);
35 }
36
37 @Override
Yuta HIGUCHI53a285d2014-10-06 23:58:01 -070038 public <T> T decode(final byte[] bytes) {
Yuta HIGUCHIad4c2182014-09-29 11:16:23 -070039 if (bytes == null) {
40 return null;
41 }
42 return serializerPool.deserialize(bytes);
43 }
44
Yuta HIGUCHIf6d11702014-09-30 19:18:59 -070045 @Override
Yuta HIGUCHI53a285d2014-10-06 23:58:01 -070046 public void encode(Object obj, ByteBuffer buffer) {
Yuta HIGUCHIf6d11702014-09-30 19:18:59 -070047 serializerPool.serialize(obj, buffer);
48 }
49
50 @Override
Yuta HIGUCHI53a285d2014-10-06 23:58:01 -070051 public <T> T decode(ByteBuffer buffer) {
Yuta HIGUCHIf6d11702014-09-30 19:18:59 -070052 return serializerPool.deserialize(buffer);
53 }
54
Yuta HIGUCHIad4c2182014-09-29 11:16:23 -070055}