All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.hepeng.commons.serializer.KryoObjectSerializer Maven / Gradle / Ivy

The newest version!
package org.hepeng.commons.serializer;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.pool.KryoPool;

import java.io.ByteArrayInputStream;

/**
 * https://github.com/EsotericSoftware/kryo/
 * @author he peng
 */
public class KryoObjectSerializer extends ExceptionTranslationObjectSerializer {

    private static final KryoPool KRYO_POOL = new KryoPool.Builder(new KryoFactoryImpl()).build();

    @Override
    protected byte[] convert(T object) throws Exception {
        Kryo kryo = KRYO_POOL.borrow();
        Output output = new Output(1024);
        kryo.writeObject(output , object);
        byte[] bytes = output.toBytes();
        output.close();
        KRYO_POOL.release(kryo);
        return bytes;
    }

    @Override
    protected T convert(byte[] bytes) throws Exception {
        Kryo kryo = KRYO_POOL.borrow();
        Input input = new Input(new ByteArrayInputStream(bytes));
        T t = kryo.readObject(input, this.serializationClass);
        input.close();
        KRYO_POOL.release(kryo);
        return t;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy