我想创建一个场景,其中我要模拟一个锁定场景。要求如下: 1. Redis中有一个Map实例,具有一个Key,Value对。 2.遍历键。 3.在迭代时,检查Key表示的值是否被其他人锁定?如果是,则继续下一个键。如果否,则进行处理。
因此,我为相同的代码编写了以下代码,但似乎在Map的每个对象上没有单独的锁,但在整个Map上。您能帮我模拟这种情况吗?
RMap < String, SomeObject > someObjectMap = redissonClient.getMap("SOME_OBJECT_MAP");
someObjectMap.put("someObject1", new SomeObject());
someObjectMap.put("someObject2", new SomeObject());
Set < String > keySet = someObjectMap.keySet();
for (String key: keySet) {
RLock lock = redissonClient.getLock("THE_LOCK");
if (lock.tryLock()) {
try {
SomeObject someObject = someObjectMap.get(key);
//do some processing on someObject instance.
//I am assuming that if there is any other lock on someObject then I will skip and proceed to the next one in the Map.
} finally {
lock.unlock();
}
} else {
continue;
}
}
为了确保我的代码正常工作,我在测试代码下面编写了代码。但是当我执行它时,它不会锁定地图的一个实例,而是锁定整个地图本身。 正如您在下面的代码中看到的那样,正在处理与键“ someObject1”关联的对象,但是当您在上面的代码中循环使用键“ someObject2”的对象时,也会被跳过。
RMap < String, SomeObject > someObjectMap = redissonClient.getMap("SOME_OBJECT_MAP");
Thread t = new Thread(() -> {
SomeObject someObject = someObjectMap.get("someObject1");
RLock lock = redissonClient.getLock("SOME_LOCK");
try {
lock.lock();
while (true) {
//do processing with someObject
}
} finally {
lock.unlock();
}
});
t.start();
请提出建议。