ReentrantReadWriteLock阻止我对对象执行操作?

时间:2019-01-05 10:15:30

标签: java multithreading concurrency reentrantreadwritelock

我有以下对象:

    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;
    }
}

我有以下内容:

    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
}

如您所见,我锁定了部分代码,以便在没有人尝试写东西的时候让线程从该代码中读取。

另外,我有以下代码:

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

现在,我知道当第一个代码块出现时,第二个代码将等待第一个代码块结束,我的问题是,是否可以在下一个代码块中读取dataStructure对象,尽管我没有提到任何ReentrantReadWriteLock锁,但有人会同时向他写信或从他读信:

String username = seperate[1];
    String password = seperate[2];
    User user = dataStructures.registeredUser.get(username);

提前谢谢!

1 个答案:

答案 0 :(得分:1)

是的,因为有人使用线程安全的ConcurrentHashMap作为registeredUser,所以您将能够在有人写或读该锁的同时从dataStructure对象读取数据。

如果您对注册用户使用普通的HashMap,仍将允许您从registeredUser读取数据,但是您会看到不正确/过时的数据,因为普通的HashMap不是线程安全的,并且您访问时没有锁。