diff --git a/rpc-framework-simple/src/main/java/github/javaguide/serialize/protostuff/ProtostuffSerializer.java b/rpc-framework-simple/src/main/java/github/javaguide/serialize/protostuff/ProtostuffSerializer.java index 2a0c60c7a7a2aebf0b6798fc06fbf1972a05a611..86f55be49679abfcb8e3edb86f4269eca6515753 100644 --- a/rpc-framework-simple/src/main/java/github/javaguide/serialize/protostuff/ProtostuffSerializer.java +++ b/rpc-framework-simple/src/main/java/github/javaguide/serialize/protostuff/ProtostuffSerializer.java @@ -12,20 +12,20 @@ import io.protostuff.runtime.RuntimeSchema; */ public class ProtostuffSerializer implements Serializer { - /** - * Avoid re applying buffer space every time serialization - */ - private static final LinkedBuffer BUFFER = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE); - @Override public byte[] serialize(Object obj) { + //1 Avoid re applying buffer space every time serialization + //2 Local variables can avoid index out of bounds caused by concurrency + //3 Class static variables are prone to exceptions due to concurrency + final LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE); + Class clazz = obj.getClass(); Schema schema = RuntimeSchema.getSchema(clazz); byte[] bytes; try { - bytes = ProtostuffIOUtil.toByteArray(obj, schema, BUFFER); + bytes = ProtostuffIOUtil.toByteArray(obj, schema, buffer); } finally { - BUFFER.clear(); + buffer.clear(); } return bytes; }