0

Where should a class like this add try-with-resources so that it correctly closes resources? I presume the appender should be reused as shown, right?

public class ChronicleWriter implements UpdateListener {
  private ExcerptAppender appender;
  private SingleChronicleQueue queue;

  public ChronicleWriter(Path p) {
    queue = SingleChronicleQueueBuilder.binary(p).build();
    appender = queue.acquireAppender();
  }

  @Override
  public void onUpdate(String text) {
    appender.writeText(text);
  }
}
Andrew
  • 1,031
  • 10
  • 24

1 Answers1

0

queue.acquireAppender() call will acquire appender from thread local pool of weak references so there's little point reusing it, moreover it's dangerous unless your component is guaranteed to be used only in single thread as appenders are not thread safe.

The usual try-with-resources pattern we use is as follows:

try (final DocumentContext dc = queue.acquireAppender().writingDocument()) {
    dc.wire().write("eventName").float32(Float.NaN);
}

Additionally you might want to make your class closeable and add:

public void close() {
    net.openhft.chronicle.core.io.Closeable.closeQuietly(queue);
}
Dmitry Pisklov
  • 1,196
  • 1
  • 6
  • 16