我知道使用destroy方法手动删除了Hazelcast锁,我可以使用IMap自动删除锁。但是如果我使用条件该怎么办?
线程1
ILock lock = hazelcastInstance.getLock(transactionId);
lock.lock();
try {
boolean signaled = lock.newCondition("someCondition").await(waitInterval, TimeUnit.MILLISECONDS);
// work 2
} finally {
lock.unlock();
}
线程2
ILock lock = hazelcastInstance.getLock(transactionId);
lock.lock();
try {
// work 1
lock.newCondition("someCondition").signalAll();
} finally {
lock.unlock();
}
我无法使用ILock,因为我有很多交易而且会导致内存泄漏(我无法为ILock调用destroy,因为我不知道何时可以执行此操作) 。使用IMap锁定/解锁时,内存泄漏没有问题,但我无法使用ICondition。
现在我创建了地图和两套:
IMap<Long, ?> idLockingMap = hazelcastInstance.getMap("idLocking");
Set<Long> waitingTrans = hazelcastInstance.getSet("waitSet");
Set<Long> signaledTrans = hazelcastInstance.getSet("notifySet");
线程1
//part of run method
idLockingMap.lock(transactionId);
try {
boolean signaled = await(transactionId, 10000);
// work 2
} finally {
idLockingMap.unlock(transactionId);
}
private boolean await(final Long trId, long waitInterval) throws InterruptedException {
long start = System.currentTimeMillis();
waitingTrans.add(trId)
idLockingMap.unlock(trId);
try {
while (System.currentTimeMillis() - start < waitInterval) {
if (signaledTrans.contains(trId)) {
return true;
}
Thread.sleep(250);
}
} finally {
idLockingMap.lock(trId);
signaledTrans.remove(trId);
waitingTrans.remove(trId);
}
return false;
}
线程2
//part of run method
idLockingMap.lock(transactionId);
try {
// work 1
if (waitingTrans.contains(transactionId)) {
signaledTrans.add(transactionId)
}
} finally {
idLockingMap.unlock(transactionId);
}
使用Hazelcast有简单的方法吗?