Terminate a transaction

You can terminate (abort) a long-running transaction from another thread.

The source code for the examples can befound at: TerminateTransactions.java

First, start the database server:

DatabaseManagementService managementService = new DatabaseManagementServiceBuilder( databaseDirectory ).build();
GraphDatabaseService graphDb = managementService.database( DEFAULT_DATABASE_NAME );

Then, start creating an infinite binary tree of nodes in the database as an example of a long-running transaction:

RelationshipType relType = RelationshipType.withName( "CHILD" );
Queue<Node> nodes = new LinkedList<>();
int depth = 1;

try ( Transaction tx = graphDb.beginTx() )
{
    Node rootNode = tx.createNode();
    nodes.add( rootNode );

    for (; true; depth++) {
        int nodesToExpand = nodes.size();
        for (int i = 0; i < nodesToExpand; ++i) {
            Node parent = nodes.remove();

            Node left = tx.createNode();
            Node right = tx.createNode();

            parent.createRelationshipTo( left, relType );
            parent.createRelationshipTo( right, relType );

            nodes.add( left );
            nodes.add( right );
        }
    }
}
catch ( TransactionTerminatedException ignored )
{
    return String.format( "Created tree up to depth %s in 1 sec", depth );
}

After waiting for some time, terminate the transaction from a separate thread:

tx.terminate();

Running this executes the long-running transaction for about one second and prints the maximum depth of the tree that had been created before the transaction was terminated. No changes have been made to the data (because of the transaction’s termination) and the result is as if no operations have been performed.

This is an example output:

Created tree up to depth 18 in 1 sec

Finally, the database can be shut down again:

managementService.shutdown();