2 * Copyright 2014-present Open Networking Foundation
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package io.atomix.utils.serializer;
18 import com.esotericsoftware.kryo.Kryo;
19 import com.esotericsoftware.kryo.Registration;
20 import com.esotericsoftware.kryo.Serializer;
21 import com.esotericsoftware.kryo.io.ByteBufferInput;
22 import com.esotericsoftware.kryo.io.ByteBufferOutput;
23 import com.esotericsoftware.kryo.pool.KryoCallback;
24 import com.esotericsoftware.kryo.pool.KryoFactory;
25 import com.esotericsoftware.kryo.pool.KryoPool;
26 import com.google.common.base.MoreObjects;
27 import com.google.common.collect.ImmutableList;
28 import org.objenesis.strategy.StdInstantiatorStrategy;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
32 import java.io.ByteArrayInputStream;
33 import java.io.InputStream;
34 import java.io.OutputStream;
35 import java.nio.ByteBuffer;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.List;
40 import java.util.Map.Entry;
41 import java.util.Objects;
43 import static java.util.Objects.requireNonNull;
46 * Pool of Kryo instances, with classes pre-registered.
49 public final class Namespace implements KryoFactory, KryoPool {
52 * Default buffer size used for serialization.
54 * @see #serialize(Object)
56 public static final int DEFAULT_BUFFER_SIZE = 4096;
59 * ID to use if this KryoNamespace does not define registration id.
61 private static final int FLOATING_ID = -1;
64 * Smallest ID free to use for user defined registrations.
66 private static final int INITIAL_ID = 16;
68 static final String NO_NAME = "(no name)";
70 private static final Logger LOGGER = LoggerFactory.getLogger(Namespace.class);
72 private final KryoPool kryoPool = new KryoPool.Builder(this).softReferences().build();
74 private final KryoOutputPool kryoOutputPool = new KryoOutputPool();
75 private final KryoInputPool kryoInputPool = new KryoInputPool();
77 private final ImmutableList<RegistrationBlock> registeredBlocks;
79 private final ClassLoader classLoader;
80 private final String friendlyName;
83 * KryoNamespace builder.
86 public static final class Builder {
87 private int blockHeadId = INITIAL_ID;
88 private List<Entry<Class<?>[], Serializer<?>>> types = new ArrayList<>();
89 private List<RegistrationBlock> blocks = new ArrayList<>();
90 private ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
93 * Builds a {@link Namespace} instance.
95 * @return KryoNamespace
97 public Namespace build() {
98 return build(NO_NAME);
102 * Builds a {@link Namespace} instance.
104 * @param friendlyName friendly name for the namespace
105 * @return KryoNamespace
107 public Namespace build(String friendlyName) {
108 if (!types.isEmpty()) {
109 blocks.add(new RegistrationBlock(this.blockHeadId, types));
111 return new Namespace(blocks, classLoader, friendlyName);
115 * Registers serializer for the given set of classes.
117 * When multiple classes are registered with an explicitly provided serializer, the namespace guarantees
118 * all instances will be serialized with the same type ID.
120 * @param classes list of classes to register
121 * @param serializer serializer to use for the class
124 public Builder register(Serializer<?> serializer, final Class<?>... classes) {
125 types.add(Map.entry(classes, serializer));
130 * Sets the namespace class loader.
132 * @param classLoader the namespace class loader
133 * @return the namespace builder
135 public Builder setClassLoader(ClassLoader classLoader) {
136 this.classLoader = classLoader;
142 * Creates a new {@link Namespace} builder.
146 public static Builder builder() {
147 return new Builder();
151 * Creates a Kryo instance pool.
153 * @param registeredTypes types to register
154 * @param registrationRequired whether registration is required
155 * @param friendlyName friendly name for the namespace
158 final List<RegistrationBlock> registeredTypes,
159 ClassLoader classLoader,
160 String friendlyName) {
161 this.registeredBlocks = ImmutableList.copyOf(registeredTypes);
162 this.classLoader = classLoader;
163 this.friendlyName = requireNonNull(friendlyName);
165 // Pre-populate with a single instance
170 * Serializes given object to byte array using Kryo instance in pool.
172 * Note: Serialized bytes must be smaller than {@link #MAX_BUFFER_SIZE}.
174 * @param obj Object to serialize
175 * @return serialized bytes
177 public byte[] serialize(final Object obj) {
178 return serialize(obj, DEFAULT_BUFFER_SIZE);
182 * Serializes given object to byte array using Kryo instance in pool.
184 * @param obj Object to serialize
185 * @param bufferSize maximum size of serialized bytes
186 * @return serialized bytes
188 public byte[] serialize(final Object obj, final int bufferSize) {
189 return kryoOutputPool.run(output -> {
190 return kryoPool.run(kryo -> {
191 kryo.writeClassAndObject(output, obj);
193 return output.getByteArrayOutputStream().toByteArray();
199 * Serializes given object to byte buffer using Kryo instance in pool.
201 * @param obj Object to serialize
202 * @param buffer to write to
204 public void serialize(final Object obj, final ByteBuffer buffer) {
205 ByteBufferOutput out = new ByteBufferOutput(buffer);
206 Kryo kryo = borrow();
208 kryo.writeClassAndObject(out, obj);
216 * Serializes given object to OutputStream using Kryo instance in pool.
218 * @param obj Object to serialize
219 * @param stream to write to
221 public void serialize(final Object obj, final OutputStream stream) {
222 serialize(obj, stream, DEFAULT_BUFFER_SIZE);
226 * Serializes given object to OutputStream using Kryo instance in pool.
228 * @param obj Object to serialize
229 * @param stream to write to
230 * @param bufferSize size of the buffer in front of the stream
232 public void serialize(final Object obj, final OutputStream stream, final int bufferSize) {
233 ByteBufferOutput out = new ByteBufferOutput(stream, bufferSize);
234 Kryo kryo = borrow();
236 kryo.writeClassAndObject(out, obj);
244 * Deserializes given byte array to Object using Kryo instance in pool.
246 * @param bytes serialized bytes
247 * @param <T> deserialized Object type
248 * @return deserialized Object
250 public <T> T deserialize(final byte[] bytes) {
251 return kryoInputPool.run(input -> {
252 input.setInputStream(new ByteArrayInputStream(bytes));
253 return kryoPool.run(kryo -> {
254 @SuppressWarnings("unchecked")
255 T obj = (T) kryo.readClassAndObject(input);
258 }, DEFAULT_BUFFER_SIZE);
262 * Deserializes given byte buffer to Object using Kryo instance in pool.
264 * @param buffer input with serialized bytes
265 * @param <T> deserialized Object type
266 * @return deserialized Object
268 public <T> T deserialize(final ByteBuffer buffer) {
269 ByteBufferInput in = new ByteBufferInput(buffer);
270 Kryo kryo = borrow();
272 @SuppressWarnings("unchecked")
273 T obj = (T) kryo.readClassAndObject(in);
281 * Deserializes given InputStream to an Object using Kryo instance in pool.
283 * @param stream input stream
284 * @param <T> deserialized Object type
285 * @return deserialized Object
287 public <T> T deserialize(final InputStream stream) {
288 return deserialize(stream, DEFAULT_BUFFER_SIZE);
292 * Deserializes given InputStream to an Object using Kryo instance in pool.
294 * @param stream input stream
295 * @param <T> deserialized Object type
296 * @param bufferSize size of the buffer in front of the stream
297 * @return deserialized Object
299 public <T> T deserialize(final InputStream stream, final int bufferSize) {
300 ByteBufferInput in = new ByteBufferInput(stream, bufferSize);
301 Kryo kryo = borrow();
303 @SuppressWarnings("unchecked")
304 T obj = (T) kryo.readClassAndObject(in);
312 * Creates a Kryo instance.
314 * @return Kryo instance
317 public Kryo create() {
318 LOGGER.trace("Creating Kryo instance for {}", this);
319 Kryo kryo = new Kryo();
320 kryo.setClassLoader(classLoader);
321 kryo.setRegistrationRequired(true);
323 // TODO rethink whether we want to use StdInstantiatorStrategy
324 kryo.setInstantiatorStrategy(
325 new Kryo.DefaultInstantiatorStrategy(new StdInstantiatorStrategy()));
327 for (RegistrationBlock block : registeredBlocks) {
328 int id = block.begin();
329 if (id == FLOATING_ID) {
330 id = kryo.getNextRegistrationId();
332 for (Entry<Class<?>[], Serializer<?>> entry : block.types()) {
333 register(kryo, entry.getKey(), entry.getValue(), id++);
340 * Register {@code type} and {@code serializer} to {@code kryo} instance.
342 * @param kryo Kryo instance
343 * @param types types to register
344 * @param serializer Specific serializer to register or null to use default.
345 * @param id type registration id to use
347 private void register(Kryo kryo, Class<?>[] types, Serializer<?> serializer, int id) {
348 Registration existing = kryo.getRegistration(id);
349 if (existing != null) {
350 boolean matches = false;
351 for (Class<?> type : types) {
352 if (existing.getType() == type) {
359 LOGGER.error("{}: Failed to register {} as {}, {} was already registered.",
360 friendlyName, types, id, existing.getType());
362 throw new IllegalStateException(String.format(
363 "Failed to register %s as %s, %s was already registered.",
364 Arrays.toString(types), id, existing.getType()));
366 // falling through to register call for now.
367 // Consider skipping, if there's reasonable
368 // way to compare serializer equivalence.
371 for (Class<?> type : types) {
372 Registration r = null;
373 if (serializer == null) {
374 r = kryo.register(type, id);
375 } else if (type.isInterface()) {
376 kryo.addDefaultSerializer(type, serializer);
378 r = kryo.register(type, serializer, id);
381 if (r.getId() != id) {
382 LOGGER.debug("{}: {} already registered as {}. Skipping {}.",
383 friendlyName, r.getType(), r.getId(), id);
385 LOGGER.trace("{} registered as {}", r.getType(), r.getId());
391 public Kryo borrow() {
392 return kryoPool.borrow();
396 public void release(Kryo kryo) {
397 kryoPool.release(kryo);
401 public <T> T run(KryoCallback<T> callback) {
402 return kryoPool.run(callback);
406 public String toString() {
407 if (!NO_NAME.equals(friendlyName)) {
408 return MoreObjects.toStringHelper(getClass())
410 .add("friendlyName", friendlyName)
411 // omit lengthy detail, when there's a name
414 return MoreObjects.toStringHelper(getClass())
415 .add("registeredBlocks", registeredBlocks)
419 static final class RegistrationBlock {
420 private final int begin;
421 private final ImmutableList<Entry<Class<?>[], Serializer<?>>> types;
423 RegistrationBlock(int begin, List<Entry<Class<?>[], Serializer<?>>> types) {
425 this.types = ImmutableList.copyOf(types);
432 public ImmutableList<Entry<Class<?>[], Serializer<?>>> types() {
437 public String toString() {
438 return MoreObjects.toStringHelper(getClass())
445 public int hashCode() {
446 return types.hashCode();
449 // Only the registered types are used for equality.
451 public boolean equals(Object obj) {
456 if (obj instanceof RegistrationBlock) {
457 RegistrationBlock that = (RegistrationBlock) obj;
458 return Objects.equals(this.types, that.types);