Skip to content

Commit

Permalink
[More Optimize]Heartbeat skip serialize and deserialize (apache#7168)
Browse files Browse the repository at this point in the history
* 对于心跳的Request、Response,序列化时获取已缓存的null对象的序列化后字节,反序列化时则赋值null,以降低心跳对CPU带来的开销。

* rename method getNullBytes(s) -> getNullBytesOf(s)

* format code

* Use byte array comparison to identify the event is heartbeats

* Use NIO-ThreadLocal buffer to read event payload, to reduce mem cost.
  • Loading branch information
zhangyz-hd authored Feb 8, 2021
1 parent d70b151 commit 75f04bf
Showing 1 changed file with 11 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ public class CodecSupport {
private static Map<String, Byte> SERIALIZATIONNAME_ID_MAP = new HashMap<String, Byte>();
// Cache null object serialize results, for heartbeat request/response serialize use.
private static Map<Byte, byte[]> ID_NULLBYTES_MAP = new HashMap<Byte, byte[]>();
// NIO ThreadLocal buffer to read event payload
private static final ThreadLocal<byte[]> TL_BUFFER = ThreadLocal.withInitial(() -> new byte[1024]);

static {
Set<String> supportedExtensions = ExtensionLoader.getExtensionLoader(Serialization.class).getSupportedExtensions();
Expand Down Expand Up @@ -132,7 +134,7 @@ public static byte[] getNullBytesOf(Serialization s) {
*/
public static byte[] getPayload(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
byte[] buffer = getBuffer(is.available());
int len;
while ((len = is.read(buffer)) > -1) {
baos.write(buffer, 0, len);
Expand All @@ -141,6 +143,14 @@ public static byte[] getPayload(InputStream is) throws IOException {
return baos.toByteArray();
}

private static byte[] getBuffer(int size) {
byte[] bytes = TL_BUFFER.get();
if (size <= bytes.length) {
return bytes;
}
return new byte[size];
}

/**
* Check if payload is null object serialize result byte[] of serialization
*
Expand Down

0 comments on commit 75f04bf

Please sign in to comment.