1

I have a question about how the Chronicle queue avoids garbage collection:

I understand that the Chronicle queue uses a memory mapping file so that it can save an object into main memory or dist rather than into JVM. However, when a processor deserializes the object from the main memory, it still needs to create a new instance. So where exactly Chronicle queue avoid garbage collection?

See the below case that comes from a Chronicle github example. When performs write to/read operation, it still needs to create a new instance using MyObject me = new MyObject() and "me" will be garbaged collected.

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);
    }

}
Guifan Li
  • 1,543
  • 5
  • 14
  • 28

1 Answers1

2

You can reuse the object you deserialise into.

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

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

The String is also pooled reducing garbage.

This way you can write and read millions of messages but only create one or two objects.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130