首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Neo4j:通过Java API或Cypher显式悲观锁定

Neo4j:通过Java API或Cypher显式悲观锁定
EN

Stack Overflow用户
提问于 2018-04-25 09:48:52
回答 2查看 209关注 0票数 2

有没有办法通过Neo4J、Java API或Cypher手动获取某组节点上的写锁?

examples in documentation,但仅适用于嵌入式Neo4j版本。标准的Java Transaction接口不包含这样的方法:https://neo4j.com/docs/api/java-driver/current/org/neo4j/driver/v1/Transaction.html

另外,我也找不到通过Cypher来实现的方法。

EN

回答 2

Stack Overflow用户

发布于 2018-04-25 09:54:07

您可以通过写入节点来获取写锁,例如通过设置或移除属性。我认为这在删除不存在的属性时也是有效的。

如果安装了APOC Procedures,则可以调用apoc.lock.nodes()过程,向其传递要锁定的节点列表。

票数 2
EN

Stack Overflow用户

发布于 2019-10-26 16:07:12

为了扩展@InverseFalcon的答案,这里有一个通过写入节点实现写锁的示例:

代码语言:javascript
复制
@Test
public void testPessimisticLocking() throws InterruptedException {
    txn.execute(status -> {
        session.query("CREATE (n:Lock {uuid:'test'})", Map.of(), false);
        return null;
    });

    ExecutorService executor = Executors.newFixedThreadPool(2);
    Runnable task = () -> {
        LOG.debug("Starting task");

        txn.execute(status -> {
            long time = System.nanoTime();
            LOG.debug("Locking node with time={}", time);
            session.query("MATCH (n:Lock {uuid:'test'}) SET n.time = {0}", Map.of("0", time), false);

            LOG.debug("Query done, waiting some time...");
            try {
                Thread.sleep(5000);
            }
            catch (InterruptedException e) {
                LOG.warn("Interrupted", e);
            }
            LOG.debug("Waiting done");

            return null;
        });

        LOG.debug("Finished task");
    };

    for (int i = 0; i < 2; i++) {
        executor.execute(task);
    }

    executor.shutdown();
    executor.awaitTermination(20, TimeUnit.MINUTES);
}

该测试创建一个标签为"Lock“的节点。它并行启动两个任务,试图获取节点上的写锁。一旦获得锁,每个任务在事务中等待5秒(模拟工作负载)。调试输出为:

代码语言:javascript
复制
2019-10-26 09:47:09,502 [pool-3-thread-1] DEBUG - Starting task
2019-10-26 09:47:09,508 [pool-3-thread-1] DEBUG - Locking node with time=82297334790500
2019-10-26 09:47:09,513 [pool-3-thread-2] DEBUG - Starting task
2019-10-26 09:47:09,515 [pool-3-thread-2] DEBUG - Locking node with time=82297342219000
2019-10-26 09:47:09,605 [pool-3-thread-2] DEBUG - Query done, waiting some time...
2019-10-26 09:47:14,627 [pool-3-thread-2] DEBUG - Waiting done
2019-10-26 09:47:14,643 [pool-3-thread-1] DEBUG - Query done, waiting some time...
2019-10-26 09:47:14,645 [pool-3-thread-2] DEBUG - Finished task
2019-10-26 09:47:19,643 [pool-3-thread-1] DEBUG - Waiting done
2019-10-26 09:47:19,841 [pool-3-thread-1] DEBUG - Finished task

在日志中,您可以看到就在另一个任务完成事务时,另一个任务正在获取锁。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50012912

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档