【发布时间】:2019-03-05 14:27:52
【问题描述】:
public int saveUserToMap(User user) {
ReentrantLock lock;
if(this.userLocks.containsKey(user.getId())) {
lock = this.userLocks.get(user.getId());
} else {
lock = new ReentrantLock();
ReentrantLock check = this.userLocks.putIfAbsent(user.getId(), lock);
if(check != null)
lock = check;
}
if(lock.isLocked())
try {
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lock.lock();
this.users.put(user.getId(), user);
this.usersByName.put(user.getUsername(), user);
this.usersByEmail.put(user.getEmail(), user);
lock.unlock();
lock.notify();
return user.getId();
}
嘿,我只是想请 Java 开发人员检查我的代码是否是线程安全的并且没有死锁,因为我想在我的项目中使用它。 Users、UsersByName 和 UsersByEmail 是 ConcurrentHashMap,其中 String、Integer 为 key,User 对象为 Value。 UserLocks 是一个 ConcurrentHashMap,其中 Integer(显然用户 id 作为键)和 ReentrantLock 作为值。 我想同步三个HashMap。 如果有人有更好的解决方案来制作包含三个键的并发映射,那么最好将其发布在这里。性能也很重要。
【问题讨论】:
-
我要同步三个HashMap有什么目的?
-
这三个 hashmap 的 value 相同但 key 不同。我不希望这样,因为多线程三个哈希图具有不同的值。比如id、username、email的用户在三个hashmap中表示,现在两个线程要更新用户,我不希望三个hashmap有不同的值。
-
我担心如果 2 个具有相同 ID、用户名或电子邮件但不是全部 3 个的
User实体被添加到您的地图中会发生什么?其他地方是否考虑到了这一点?
标签: java concurrency thread-safety deadlock