简体   繁体   中英

Is double-checked locking only broken in a lazy initialization scene?

I read this article: The "Double-Checked Locking is Broken" Declaration , it says

Double-Checked Locking is widely cited and used as an efficient method for implementing lazy initialization in a multithreaded environment.

Unfortunately, it will not work reliably in a platform independent way when implemented in Java...

And this article: Double-checked locking: Clever, but broken , it says:

The DCL idiom was designed to support lazy initialization...

My questions are:

  1. Is double-checked locking only broken when trying to do lazy initialization ?

  2. Is it also broken in a scene like the code below (all things are already initialized) ?

code:

public String refreshJsapiTicket() throws WxErrorException {

  if (wxMpConfigStorage.isJsapiTicketExpired()) {
    synchronized (wxMpConfigStorage) {
      if (wxMpConfigStorage.isJsapiTicketExpired()) {
        // ...
        // update 
        wxMpConfigStorage.setJsapiTicket(jsapiTicket, expiresInSeconds);
      }
    }
  }

}

public class WxMpInMemoryConfigStorage implements WxMpConfigStorage {

  protected volatile String jsapiTicket;
  protected volatile long jsapiTicketExpiresTime;

  public synchronized void updateJsapiTicket(String jsapiTicket, int expiresInSeconds) {
    this.jsapiTicket = jsapiTicket;
    this.jsapiTicketExpiresTime = System.currentTimeMillis() + (expiresInSeconds - 200) * 1000l;
  }

}

Answer to your 1: Yes. From Java 5 class loader guarantees the single or one time initialization for static fields. Answer to your 2: From code its not clear but it depends what you reading in wxMpConfigStorage.isJsapiTicketExpired() method. If you deciding based on reading something which is not thread safe then yes DCL can fail. But in your case jsapiTicketExpiresTime is volatile and so thread safe to read and so DCL will work for you.

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