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