Search code examples
javalambdachroniclechronicle-queue

Chronicle Queue: Usage with less or no lambdas


The documentation shows the usage of an appender or a tailer generally with a lambda, like this:

appender.writeDocument(wireOut -> wireOut.write("log").marshallable(m ->
      m.write("mkey").text(mkey)
       .write("timestamp").dateTime(now)
       .write("msg").text(data)));

For a tailer I I use:

   int count = 0;
   while (read from tailer ) { 
      wire.read("log").marshallable(m -> {
             String mkey = m.read("mkey").text();
            LocalDateTime ts = m.read("timestamp").dateTime();
             String bmsg = m.read("msg").text();
         //... do more stuff, like updating counters
             count++;
       }
   }

During the read I would like to do stuff like updating counters, but this is not possible in lambda (needs "effectively final" values/objects).

  • What is good practice for using the API without lambdas?
  • Any other ideas on how to do this? (Currently I use AtomicInteger objects)

Solution

  • static class Log extends AbstractMarshallable {
        String mkey;
        LocalDateTime timestamp;
        String msg;
    }
    
    int count;
    
    public void myMethod() {
        Log log = new Log();
        final SingleChronicleQueue q = SingleChronicleQueueBuilder.binary(new File("q4")).build();
        final ExcerptAppender appender = q.acquireAppender();
        final ExcerptTailer tailer = q.createTailer();
    
        try (final DocumentContext dc = appender.writingDocument()) {
            // this will store the contents of log to the queue
            dc.wire().write("log").marshallable(log);
        }
    
        try (final DocumentContext dc = tailer.readingDocument()) {
            if (!dc.isData())
                 return;
            // this will replace the contents of log
            dc.wire().read("log").marshallable(log);
            //... do more stuff, like updating counters
            count++;
        }
    }