我几次遇到这种情况.你需要的是一个单独的LockFactory,它实际上是一个锁对象弱引用的字典.代码应该是这样的:
class LockFactory {
private LockFactory() {}
private LockFactory instance = null;
public static LockFactory getInstance() {
if (this.instance == null)
this.instance = new LockFactory();
return this.instance;
}
private int _last_check_size = 0;
private int _cleanup_size = 1000;
private Map weakRefDictionary = new HashMap();
public object getLock(String id) {
synchronized(this) {
if (!this.weakRefDictionary.containsKey(id))
this.weakRefDictionary.put(id, new WeakReference(null));
Object lock = this.weakRefDictionary.get(id).Target;
if (lock == null) {
lock = new Object();
this.weakRefDictionary.get(id).Target = lock;
}
if (this.weakRefDictionary.size() > this._last_check_size + this._cleanup_size)
this._do_cleanup();
return lock;
}
}
public void _do_cleanup() {
synchronized(this) {
Iterator> iter = this.weakRefDictionary.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = iter.next();
if (entry.getValue().get() == null) {
iter.remove();
}
}
this._last_check_size = this.weakRefDictionary.size();
}
}
}
现在在你的情况下使用只需:
public void beforeUpdated(Log log){
synchronized(LockFactory.getInstance().getLock(log.getUuid())){
query(log);
merge(log);
persist(log);
}
}