4.5. Managing resources when not using transactions

It is recommended to always open a transaction when accessing the database. While it is possible to perform read only operations without opening a transaction, it is advised that you open transactions anyhow. Otherwise you should take care to close any ResourceIterators that you retrieve (generally these come from ResourceIterables). If these ResourceIterators are not closed, files and other resources will be kept open for a long time, potentially blocking other operations. The best way to ensure this, is to close each ResourceIterator in a finally-block.

What follows is an example of how to close a ResourceIterator. The example is taken from Section 4.4, “User database with schema based indexing”.

Label label = DynamicLabel.label( "User" );
int idToFind = 45;
String nameToFind = "user" + idToFind + "@neo4j.org";
ResourceIterator<Node> users = graphDb.findNodesByLabelAndProperty( label, "username", nameToFind ).iterator();
try
{
    while ( users.hasNext() )
    {
        Node node = users.next();
        System.out.println( "The username of user " + idToFind + " is " + node.getProperty( "username" ) );
    }
}
finally
{
    // alternatively use a transaction
    users.close();
}