有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java编年史队列:使用较少或没有lambda

文档显示了appender或tailer通常与lambda一起使用,如下所示:

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) 个答案

  1. # 1 楼答案

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