终止事务

您可以从另一个线程终止(中止)长时间运行的事务。

示例的源代码可在以下位置找到: TerminateTransactions.java

首先,启动数据库服务器

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

然后,在数据库中开始创建一个无限的二叉树节点,以示例长时间运行的事务

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 );
}

等待一段时间后,从另一个线程终止事务

tx.terminate();

运行此示例会执行约一秒的长时间运行事务,并打印在事务被终止前已创建的树的最大深度。由于事务被终止,数据未发生任何更改,结果相当于没有执行任何操作。

以下是示例输出

Created tree up to depth 18 in 1 sec

最后,可以再次关闭数据库

managementService.shutdown();