Chronicle Queue:少量或没有lambda的用法

时间:2017-03-06 16:07:48

标签: java lambda chronicle chronicle-queue

文档显示了通常使用lambda的appender或tailer的用法,如下所示:

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

对于我使用的尾标:

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

在阅读期间,我想做更新计数器之类的事情,但这在lambda中是不可能的(需要"有效的最终"值/对象)。

  • 使用没有lambdas的API有什么好的做法?
  • 关于如何做到这一点的任何其他想法? (目前我使用的是AtomicInteger对象)

1 个答案:

答案 0 :(得分:2)

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