我有一个关于Chronicle队列如何避免垃圾收集的问题:
据我所知,Chronicle队列使用内存映射文件,因此它可以将对象保存到主内存或dist而不是JVM中。但是,当处理器从主内存反序列化对象时,仍然需要创建一个新实例。那么Chronicle队列究竟在哪里避免垃圾收集?
请参阅以下来自Chronicle github示例的案例。当执行写入/读取操作时,它仍然需要使用MyObject创建一个新实例me = new MyObject()并且“me”将被收集。
public class Example {
static class MyObject implements Marshallable {
String name;
int age;
@Override
public String toString() {
return Marshallable.$toString(this);
}
}
public static void main(String[] args) throws IOException {
// will write the .cq4 file to working directory
SingleChronicleQueue queue = SingleChronicleQueueBuilder.builder().path(Files
.createTempDirectory("queue").toFile()).build();
ExcerptAppender appender = queue.acquireAppender();
ExcerptTailer tailer = queue.createTailer();
MyObject me = new MyObject();
me.name = "rob";
me.age = 40;
// write 'MyObject' to the queue
appender.writeDocument(me);
// read 'MyObject' from the queue
MyObject result = new MyObject();
tailer.readDocument(result);
System.out.println(result);
}
}
您可以重复使用反序列化的对象。
// created once
MyObject result = new MyObject();
// this can be called multiple times with the same object
tailer.readDocument(result);
String
也汇集减少垃圾。
这样,您可以编写和读取数百万条消息,但只能创建一个或两个对象。