Reputation: 89
I have the following object:
public class DataStructures {
public Map<String, User> registeredUser;
private ReadWriteLock readWriteLock;
public DataStructures() {
this.registeredUser = new ConcurrentHashMap<>();
readWriteLock = new ReentrantReadWriteLock(true);
}
public ReadWriteLock getReadWriteLock() {
return readWriteLock;
}
}
I Have the following block:
if(user != null && user.status()) {
String userNameList = "";
dataStructures.getReadWriteLock().readLock().lock();//ReentrantReadWriteLock
List<User> userList = new ArrayList<>(dataStructures.registeredUser.values());
//Will perform a sort on the userlist according their initial registration number
Collections.sort(userList, Comparator.comparing(User::getRegistrationId));
for (User tmpUser : userList) {
userNameList += tmpUser.getUsername() + " ";
}
connections.send(connectionId, "10 " + "7 " + userList.size() + " " + userNameList);
dataStructures.getReadWriteLock().readLock().unlock();//ReentrantReadWriteLock
}
As you can see I locked part of this code in order to let thread read from this code at the time that no one try to write something.
also, I have the following code:
dataStructures.getReadWriteLock().writeLock().lock();//ReentrantReadWriteLock
if(dataStructures.registeredUser.putIfAbsent(username, new User(username, password, dataStructures.registraionId)) == null) {
connections.send(connectionId, "10 " + "01");
dataStructures.registraionId++;
}
else
connections.send(connectionId, "11 " + "01");
dataStructures.getReadWriteLock().writeLock().unlock();//ReentrantReadWriteLock
Now, I know that when the first block of code will happen the second will wait for the first to finish, my question is if in the next block of code I will be able to read from the dataStructure
object at the same time that someone will write or read from him despite I didn't mentioned any of the ReentrantReadWriteLock locks:
String username = seperate[1];
String password = seperate[2];
User user = dataStructures.registeredUser.get(username);
Thank you in advance!
Upvotes: 0
Views: 49
Reputation: 1454
Yes, you will be able to read from the dataStructure object at the same time someone will write or read holding the lock, because you are using thread-safe ConcurrentHashMap for the registeredUser.
If you would use normal HashMap for the registeredUser, you would be still allowed to read from the registeredUser but you would see incorect/stale data because normal HashMap is not thread-safe and you are accessing it without the lock.
Upvotes: 1