Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java ReentrantReadWriteLock阻止我对对象执行操作?_Java_Multithreading_Concurrency_Reentrantreadwritelock - Fatal编程技术网

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

Java ReentrantReadWriteLock阻止我对对象执行操作?,java,multithreading,concurrency,reentrantreadwritelock,Java,Multithreading,Concurrency,Reentrantreadwritelock,我的目标如下: public class DataStructures { public Map<String, User> registeredUser; private ReadWriteLock readWriteLock; public DataStructures() { this.registeredUser = new ConcurrentHashMap<>(); readWriteLock

我的目标如下:

    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;
    }
}
现在,我知道当第一个代码块出现时,第二个将等待第一个代码块完成,我的问题是,尽管我没有提到任何可重入的TreadWriteLock锁,但在下一个代码块中,我是否能够在有人写入或读取对象的同时,从
数据结构
对象中读取:

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

提前谢谢你

是的,您将能够在有人持有锁写入或读取数据结构对象的同时读取数据结构对象,因为您正在为registeredUser使用线程安全的ConcurrentHashMap


如果您对registeredUser使用普通HashMap,您仍然可以从registeredUser读取数据,但您会看到不正确/陈旧的数据,因为普通HashMap不是线程安全的,您访问它时没有锁。

谢谢!你回答了我的问题
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
String username = seperate[1];
    String password = seperate[2];
    User user = dataStructures.registeredUser.get(username);