使用byte[] 需要您在每次大小更改时分配一个新的。您无法更改 byte[] 的大小。
相反,我建议使用 out Bytes 类,该类可以调整大小而不会产生太多垃圾(仅在增长时才有时)
package run.chronicle.queue;
import net.openhft.chronicle.bytes.Bytes;
import net.openhft.chronicle.wire.BytesInBinaryMarshallable;
import net.openhft.chronicle.wire.LongConversion;
import net.openhft.chronicle.wire.MilliTimestampLongConverter;
public class Message extends BytesInBinaryMarshallable {
private final Bytes text = Bytes.allocateElasticOnHeap();
@LongConversion(MilliTimestampLongConverter.class)
private long timeStamp;
//Getters and Setters
public Bytes getText() {
return text;
}
public void setText(CharSequence text) {
this.text.clear().append(text);
}
public long getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(long timeStamp) {
this.timeStamp = timeStamp;
}
}
见这个例子https://github.com/OpenHFT/Chronicle-Queue-Demo/tree/master/messages-with-text
当使用小堆 -Xmx128m -XX:NewSize=96m -verbose:gc MessageMain 运行时,您可以看到数百万条消息不会触发任何收集。
Read 10,000,000 of 10,000,000 messages in 7.990 seconds
Read 10,000,000 of 10,000,000 messages in 6.907 seconds
[main] INFO net.openhft.chronicle.bytes.MappedFile - Took 2 ms to add mapping for test-438402668456/metadata.cq4t
Read 10,000,000 of 10,000,000 messages in 6.836 seconds
[main] INFO net.openhft.chronicle.bytes.MappedFile - Took 2 ms to add mapping for test-445239126125/metadata.cq4t
Read 10,000,000 of 10,000,000 messages in 6.883 seconds
[main] INFO net.openhft.chronicle.bytes.MappedFile - Took 3 ms to add mapping for test-452122895277/metadata.cq4t
Read 10,000,000 of 10,000,000 messages in 7.013 seconds
Read 10,000,000 of 10,000,000 messages in 6.838 seconds
[main] INFO net.openhft.chronicle.bytes.MappedFile - Took 2 ms to add mapping for test-465974753213/metadata.cq4t