JVM Client: Right way of using (and stopping) ConnectionActor

Hi. I am using the following version of the JVM client.

com.geteventstore eventstore-client_2.12 5.0.8 ``` ```

Here follows my append method (stripped off irrelevant details.)

public void appendWith(EventStreamId aStartingIdentity, List anEvents) {
ActorRef connection = null;
ActorRef writeResult = null;

try {
    connection = system.actorOf(ConnectionActor.getProps(settings));

    var eventsBuilder = new WriteEventsBuilder(aStartingIdentity.streamName())
            .expectAnyVersion();

    // ... build events

    WriteEvents writeEvents = eventsBuilder.build();
    writeResult = system.actorOf(Props.create(WriteResult.class));

    connection.tell(writeEvents, writeResult);
} catch (Exception ex) {
    throw new EventStoreAppendException(
            "Could not append to event store because: " + ex.getMessage(),
            ex);
} finally {
    if (connection != null) {
        system.stop(connection);
    }
}

}

So far I understand, connection, like other actors, is supposed to be stopped (as is being done inside the finally block) after successfully passing each message; creating a new connection without stopping the previous fails with exception: java.lang.IllegalStateException: cannot create children while terminating or terminated.

The current implementation, however, usually exits without writing any events. That happens due to premature connection stop before message could be passed to writeResult actor I suppose; adding some delay after connection.tell() results into normal operation.

What is the appropriate way of stopping connection? And what is the recommended way to implement writes in general?

I am not familiar with the JVM client, but an EventStore connection isn’t like SQL connection, you are supposed to keep the same connection as long as your application lives.

So far I understand, connection, like other actors, is supposed to be stopped

It should be a singleton. There are examples of using the JVM client here: https://github.com/EventStore/EventStore.JVM/tree/master/examples/src/main/java/eventstore/j/examples

You should use EsConnectionFactory.create to get an EsConnection instead of direct usage of ConnectionActor.

It worked as I replaced ConnectionActor with an EsConnection singleton and passing message to connection actor with calling methods on EsConnection.

The write example in the repo uses ConnectionActor instead of EsConnection; I, in fact, copied my write method from there. A write example with EsConnection would help.

Thanks.