0

Usecase : Rotation of credentials for a datastore

What I want :

  1. When updateCredentials is called, it will wait until it all threads are done fetching credentials (via the synchronize) to update the credentials to the new ones.
  2. I DO NOT want calls to doSomeQuery making each other wait to fetch credentials. This object can be used in multiple threads and its a wasteful wait.

Is there a method / pattern to achieve this? The code sample below achieves item 1 but not item 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
}
Malcolm O'Hare
  • 4,879
  • 3
  • 33
  • 53
  • I don't understand your second point, neither your doSomeQueryMethod(). Can you explain what is your goal more precisely (what you want and no only what you don't want). – davidxxx Jul 24 '16 at 06:35

1 Answers1

0

Use java.util.concurrent.locks.ReadWriteLock and its implementation ReentrantReadWriteLock. From the 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.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190