gpt4 book ai didi

java - 如何在 Neo4j 中制作唯一的序列号?

转载 作者:行者123 更新时间:2023-11-30 10:35:35 26 4
gpt4 key购买 nike

我正在编写一个非托管扩展。

由于 Neo4J 没有任何内置功能来获取序列号,所以我编写了这个方法来实现类似的功能。它与“synchronized”关键字配合使用时效果很好,但如果没有它,我在同时从多个线程调用它的测试用例中尝试使用它时遇到了 DeadlockDetectedException。

这是解决这个问题的好方法吗?

为什么我需要使方法“同步”,难道“acquireReadLock”还不够吗?

public synchronized static int getNextSequence(Node node, String property) {
int sequence = 0;
GraphDatabaseService graphDb = node.getGraphDatabase();

try(Transaction t = graphDb.beginTx()) {
t.acquireReadLock(node);

sequence = (int) node.getProperty(property);
node.setProperty(property, sequence + 1);

//The lock is automatic released on t.success().
t.success();
} catch (Exception e) {
log.error("Failed to get sequence for node: ({}), property: ({}), exception: ({})", node, property, e);
throw e;
}

return sequence;
}

编辑
在收到@cybersam 的回复后,我将 acquireReadLock 更改为 acquireWriteLock,这解决了 DeadlockProblem 问题,我不再需要使方法同步。

更新后的代码如下所示:

public static int getNextSequence(Node node, String property) {
int sequence = 0;
GraphDatabaseService graphDb = node.getGraphDatabase();

try(Transaction t = graphDb.beginTx()) {
t.acquireWriteLock(node);

sequence = (int) node.getProperty(property);
node.setProperty(property, sequence + 1);

//The lock is automatic released on t.success().
t.success();
} catch (Exception e) {
log.error("Failed to get sequence for node: ({}), property: ({}), exception: ({})", node, property, e);
throw e;
}

return sequence;
}

最佳答案

您的代码实际上是在向节点写入(以及从中读取),但您只是获取一个读锁。您必须使用 acquireWriteLock反而。一旦这样做,您应该摆脱“同步”(请参阅​​ this section of the docs 中的警告)。

关于java - 如何在 Neo4j 中制作唯一的序列号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41063918/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com