仅在更新变量时同步变量

Synchronize on variable only when it is being updated

用例:数据存储的凭据轮换

我想要什么:

  1. 调用 updateCredentials 时,它将等到所有线程完成获取凭据(通过同步)以将凭据更新为新凭据。
  2. 我不想调用 doSomeQuery 让彼此等待获取凭据。这个对象可以在多线程中使用,等待很浪费。

是否有实现此目的的方法/模式?下面的代码示例实现了第 1 项但未实现第 2 项。

private Object credentialUpdate = new Object();

public void updateCredentials(String user, String pass) {
    synchronize(credentialUpdate) {
      this.user = user;
      this.pass = pass;
    }
}

public void doSomeQuery(String query) {
    String curUser;
    String curPass; 
    synchronize(credentialUpdate) {
        curUser = this.user;
        curPass;
    }
    // execute query
}

使用 java.util.concurrent.locks.ReadWriteLock 及其实现 ReentrantReadWriteLock。来自 Javadoc:

A ReadWriteLock maintains a pair of associated locks, one for read-only operations and one for writing. The read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive.