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();
}
Hey, I just want to ask the java developers to check my code if it will be thread-safe and free of Deadlocks as I want to use it in my project. Users, UsersByName and UsersByEmail are ConcurrentHashMap with String, Integer as key and User object as Value. UserLocks is a ConcurrentHashMap with Integer (obviously the user id as key) and a ReentrantLock as value. I want to synchronize the three HashMaps. If someone has a better solution to make a Concurrent map with three keys, it would be nice to post it here. Performance is also important.