1

我有一个关于 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);
    }

}
4

1 回答 1

2

您可以重用您反序列化的对象。

// created once
MyObject result = new MyObject();

// this can be called multiple times with the same object
tailer.readDocument(result);

String还汇集减少垃圾。

通过这种方式,您可以编写和读取数百万条消息,但只能创建一两个对象。

于 2019-03-11T19:21:23.907 回答