Neo4j3.5学习笔记——中断正在运行的transaction
程序员文章站
2022-05-28 20:26:28
...
跟着官网代码学习.jpg–jdk 1.8.0 & neo4j 3.5
https://neo4j.com/docs/java-reference/current/java-embedded/
通过另一个线程终止long-running的transaction。
1:建立一个long-running transaction:在数据库中建立一个无限二进制树。
public String run() throws IOException {
FileUtils.deleteRecursively(databaseDirectory);
graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(databaseDirectory);
RelationshipType relType = RelationshipType.withName("CHILD");
Queue<Node> nodes = new LinkedList<>();
int depth = 1;
try(Transaction tx = graphDb.beginTx()) {
Node rootNode = graphDb.createNode();
nodes.add(rootNode);
Terminator terminator = new Terminator(tx);
terminator.terminateAfter(5000);
for(;true;depth++) {
int nodesToExpand = nodes.size();
for (int i=0; i<nodesToExpand; ++i) {
Node parent = nodes.remove();
Node left = graphDb.createNode();
Node right = graphDb.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 5 sec", depth);
}
finally {
graphDb.shutdown();
}
}
2:从另一个Thread中断transaction
- 由于transaction是被中断的,实际上并没有对数据进行任何更改,最后结果就像没有执行任何操作一样;
- (官网代码中建立了Terminator类,例中的Terminator{}作为构造器,初始化tx的值;)
- 新Thread先睡millis的长度,然后通过
tx.terminate()
实现中断。
Executors.newSingleThreadExecutor().submit(new Runnable() {
@Override
public void run() {
long startTime = System.currentTimeMillis();
do {
try {
Thread.sleep(millis);
}
catch(InterruptedException ignored) {
//terminated while sleeping
}
}
while((System.currentTimeMillis() - startTime) < millis);
tx.terminate();
}
});
3. 具体代码见: https://github.com/Amy996bbq/Neo4j/blob/master/learn/TerminateTransaction.java
上一篇: neo4j使用教程(1) 从搭建neo4j网络服务开始
下一篇: Neo4j文档