gpt4 book ai didi

java - Apache Curator 锁定食谱撤销

转载 作者:太空宇宙 更新时间:2023-11-04 13:17:58 26 4
gpt4 key购买 nike

我正在尝试测试 Apache Curator 中的可撤销锁定。我有两个尝试获取锁的线程。如果第一个测试获取了锁,第二个线程可以要求第一个线程释放锁,以便第二个线程可以获取它

        RetryPolicy retryPolicy = new ExponentialBackoffRetry(baseSleepTimeMills, maxRetries);
CuratorFramework client = CuratorFrameworkFactory.newClient(hosts, retryPolicy);
client.start();

final InterProcessMutex lock = new InterProcessMutex(client, lockBasePath);

Collection<String> nodes = lock.getParticipantNodes();

lock.makeRevocable(new RevocationListener<InterProcessMutex>(){

@Override
public void revocationRequested(InterProcessMutex lock1) {
try {
if(lock.isAcquiredInThisProcess()){
lock.release();
}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

});

if(nodes!=null && !nodes.isEmpty()){
Revoker.attemptRevoke(client, nodes.iterator().next());
}

if (lock.acquire(waitTimeSeconds, TimeUnit.SECONDS)) {
try {
doSomeWork(lockName);
} finally {
lock.release();
}
} else {
System.err.printf("%s timed out after %d seconds waiting to acquire lock on %s\n",
lockName, waitTimeSeconds, lockPath);
}

问题是,当第二个线程调用 attemptsRevoke 时,会在第一个进程上调用回调异步方法,但由于它是第三个线程的回调方法,如果调用 lock.release,则会抛出异常

java.lang.IllegalMonitorStateException: You do not own the lock

这是根据 API

release() Perform one release of the mutex if the calling thread is the same thread that acquired it.

所以基本上这是不可能的,因为回调将始终是另一个线程。还有其他方法可以实现这一目标吗?

感谢您的建议

-塔莎

最佳答案

您可以使用InterProcessSemaphoreMutex而不是 InterProcessMutex 来释放另一个线程中的锁。

引用:Ability to release an InterProcessMutex from another thread #117

关于java - Apache Curator 锁定食谱撤销,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33374596/

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