/** * Encodes the given object using registered Kryo serializers. Provides explicit buffer overflow protection, but * careful buffer sizing should be employed to reduce the need for this facility. * * @param o Object to encode. * * @return Encoded bytes. */ private byte[] encodeToBytes(final Object o) { int factor = 1; byte[] result = null; ByteBuffer buffer = Kryo.getContext().getBuffer(bufferSize * factor); while (result == null) { try { kryo.writeClassAndObject(buffer, o); result = new byte[buffer.flip().limit()]; buffer.get(result); } catch (final SerializationException e) { Throwable rootCause = e; while (rootCause.getCause() != null) { rootCause = rootCause.getCause(); } if (rootCause instanceof BufferOverflowException) { buffer = ByteBuffer.allocate(bufferSize * ++factor); logger.warn("Buffer overflow while encoding {}", o); } else { throw e; } } } return result; }