Fix compatible problem for Kryo 5
@@ -17,7 +17,7 @@ public class KryoValueEncoder extends AbstractValueEncoder {
protected static int IDENTITY_NUMBER = 0x4A953A82;
- private static int INIT_BUFFER_SIZE = 256;
+ private static int INIT_BUFFER_SIZE = 512;
static ThreadLocal<Object[]> kryoThreadLocal = ThreadLocal.withInitial(() -> {
Kryo kryo = new Kryo();
@@ -25,9 +25,9 @@ public class KryoValueEncoder extends AbstractValueEncoder {
// kryo.setInstantiatorStrategy(new StdInstantiatorStrategy());
// kryo.setInstantiatorStrategy(new Kryo.DefaultInstantiatorStrategy(new StdInstantiatorStrategy()));
- Output output = new Output(INIT_BUFFER_SIZE, -1);
+ byte[] buffer = new byte[INIT_BUFFER_SIZE];
- WeakReference<Output> ref = new WeakReference<>(output);
+ WeakReference<byte[]> ref = new WeakReference<>(buffer);
return new Object[]{kryo, ref};
});
@@ -38,14 +38,14 @@ public class KryoValueEncoder extends AbstractValueEncoder {
@Override
public byte[] apply(Object value) {
try {
- Object[] kryoAndOutput = kryoThreadLocal.get();
- Kryo kryo = (Kryo) kryoAndOutput[0];
- WeakReference<Output> ref = (WeakReference<Output>) kryoAndOutput[1];
- Output output = ref.get();
- if (output == null) {
- output = new Output(INIT_BUFFER_SIZE, -1);
- kryoAndOutput[1] = new WeakReference<>(output);
+ Object[] kryoAndBuffer = kryoThreadLocal.get();
+ Kryo kryo = (Kryo) kryoAndBuffer[0];
+ WeakReference<byte[]> ref = (WeakReference<byte[]>) kryoAndBuffer[1];
+ byte[] buffer = ref.get();
+ if (buffer == null) {
+ buffer = new byte[INIT_BUFFER_SIZE];
}
+ Output output = new Output(buffer, -1);
try {
if (useIdentityNumber) {
@@ -55,7 +55,10 @@ public class KryoValueEncoder extends AbstractValueEncoder {
return output.toBytes();
} finally {
//reuse buffer if possible
- output.clear();
+ if (ref.get() == null || buffer != output.getBuffer()) {
+ ref = new WeakReference<>(output.getBuffer());
+ kryoAndBuffer[1] = ref;
+ }
}
} catch (Exception e) {
StringBuilder sb = new StringBuilder("Kryo Encode error. ");
