终止事务
您可以从另一个线程终止(中止)长时间运行的事务。
示例的源代码可以在以下位置找到: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();