有什么方法可以检查RedisTemplate是否存在密钥吗?或者换句话说,existsRedisTemplate API中是否有等效的Redis 命令?
getAndIncrement的源代码是:
public final int getAndIncrement() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return current;
}
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么有一个循环.如果其他一些线程更改了值,那么它怎么可能是原子的呢?
假设值为5,然后我调用getAndIncrement(),我们期望它为6,但同时其他一些线程已将值更改为6,然后getAndIncrement()将使值为7,这是不可预期的.
我哪里错了?
代码段如下:
Map<Class<?>, ConcurrentHashMap<String, T>> m;
...
...
map = m.get(clazz);
if(map.get(param) == null){
String str = clazz.getSimpleName()+param;
String internedStr = str.intern();
synchronized(internedStr){
if(map.get(param) == null){
... // time-consuming task
map.put(param, someValue);
}
}
}
Run Code Online (Sandbox Code Playgroud)
基本上,我想锁定internedStr(这是不可变的),以便当其他线程遇到相同的条件(clazz,param)时,它等待锁定.
这样的解决方案有什么问题吗?