Managing resources when using long-running transactions

This section describes best practices for managing resources in long-running transactions.

Inside a long-running transaction it is good practice to ensure that any org.neo4j.graphdb.ResourceIterator obtained inside the transaction are closed as early as possible. This is either achieved by exhausting the iterator or by explicitly calling its close method.

Below is an example of how to work with a ResourceIterator. As you do not exhaust the iterator, you can close it explicitly using the close() method.

Label label = Label.label( "User" );
int idToFind = 45;
String nameToFind = "user" + idToFind + "@neo4j.org";
try ( Transaction tx = graphDb.beginTx();
      ResourceIterator<Node> users = tx.findNodes( label, "username", nameToFind ) )
{
    Node firstUserNode;
    if ( users.hasNext() )
    {
        firstUserNode = users.next();
    }
    users.close();
    // ... Do stuff with the firstUserNode we found ...
}