简体   繁体   中英

How to reinitialize inside synchronized block in Java?

I have a s3client which uses password with 60 days rotation policy. For that, we have a single s3client object being used but when the password rotates, all threads start giving exceptions. I want to catch and make sure only 1 of the threads reinitialize Client and others do nothing inside synchronized block. Can't figure out a way to do so.

private static AtomicBoolean initializingS3Client = new AtomicBoolean(false);

public static AmazonS3 reinitializeAndProvideS3Client() throws Exception {
    synchronized (initializingS3Client) {
        if (initializingS3Client.compareAndSet(false, true)) {
            s3Client.shutdown();
            s3Client = createAmazonS3Client();
            initializingS3Client.notifyAll();
        } else {
            initializingS3Client.wait();
        }
    }
    return s3Client;
}

You didn't share the code that does the actual error handling / trigger the re-initialize. I assume that you call the method on any occuring IOException. To avoid that eg temporal.network problems lead to thousands or millions of unwnated re-initializations I would suggest to specify a minimal time between two re-initializations. This helps also to make the code simpler:

public YourClass {
  ...
  private static final long MIN_TIME_BETWEEN_TWO_REINITIALIZES = 60 * 1_000; // 1 min
  privat static long lastReinitialize = 0; 

  public static AmazonS3 reinitializeAndProvideS3Client() throws Exception {
    synchronized (YourClass.class) {
      long now = System.currentTimeInMillis();
      if (now - lastReinitialize > MIN_TIME_BETWEEN_TWO_REINITIALIZES ) {
        s3Client.shutdown();
        s3Client = createAmazonS3Client();
        lastReinitialize = now;
      } 
      return s3Client;
    }
  }
}

I assume that the s3Client field is volatile and the s3Client implementation is thread-safe. If s3Client should not be volatile and access to it should already be synchronized by another object, then replace YourClass.class in the synchronized statement with that object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM