public boolean addKeyword(KeywordItem item) {
if (item == null) {
return false;
}
// 存在正在处理的key值则 wait
while(lock.contains(item.getKeyword())){
synchronized (lock) {
try {
logger.info("{}: Wait for other UpKeyword...", item.getKeyword());
lock.wait();
} catch (InterruptedException e) {
logger.warn("addKeyword wait: {}", e.getMessage());
}
}
}
//加到锁集
lock.add(item.getKeyword());
// 首先查询该主词所有的相关词条
KeywordItemRoot root = queryKeywordItemRoot(item);
// 添加该词
root.addKeywordItem(item);
// 遍历该词的同义词
String[] sameKeywords = item.getSameKeywords();
if (sameKeywords != null) {
// 遍历同义词
for (String sk : sameKeywords) {
if (StringUtils.isNotBlank(sk)) {
// 修改同义词key,其他不变
item.setKey(Utils.keyword2Key(sk));
// 添加同义词
root.addKeywordItem(item);
}
}
}
// 删除该词在Redis已有的同义词(oldSameKeywords)
if (item.getDownKeywords() != null) {
DeleteKeyword deleteKeyword = deleteKeyword(item.getKeyword(), item.getDownKeywords(), item.getRandom());
logger.info(deleteKeyword.toString());
}
// 将root(该主词和其他相关词条)写入Redis缓存
boolean save = saveKeywordItemRoot(root);
//处理完后, 唤醒正在wait的线程
synchronized (lock) {
lock.remove(item.getKeyword());
lock.notifyAll();
}
return save;
上面代码是从项目当中摘抄的一段代码,一开始是没有wait和notify的,后来由于出现在同时
修改redis的List数据时,出现不一致现象时,才改进了加入同步机制。