Double-checked locks improve concurrency

A lazy singleton

public class Singleton { 
  private static volatile Singleton singleton = null;
  private Singleton(){}
  public static Singleton getSingleton(){
    if(singleton == null){
      synchronized (Singleton.class){
        if(singleton == null){ singleton = new Singleton(); }
      }
    }
  return singleton; }
}

  

This way of writing is called "double-checked lock", mainly in the getSingleton() method, which performs two null checks. This can greatly improve concurrency and thus improve performance. After all, there are very few new cases in singletons, and most of them are parallel read operations. Therefore, performing one more null check before locking can reduce most of the locking operations and improve the execution efficiency. But it must be noted that the volatile keyword has two layers of semantics. The first layer of semantics is visibility. Visibility means that the modification of the variable in a thread will immediately be written back to the main memory (Main Memory) from the work memory (Work Memory), so other threads will immediately read the modified variable. Value, about working memory and main memory can be simply understood as cache (dealing directly with CPU) and main memory (daily speaking of memory), note that working memory is exclusive to threads, and main memory is shared by threads. The second layer of semantics of volatile is to prohibit instruction reordering optimization. The code we write (especially multi-threaded code), due to compiler optimizations, may actually be executed in a different order than the order we wrote. The compiler only guarantees that the program execution result is the same as the source code, but does not guarantee that the order of the actual instructions is the same as the source code. This is not a problem in a single thread, but once a multi-threaded environment is introduced, this disorder may cause serious problems. The volatile keyword can solve this problem semantically. It is worth noting that the volatile prohibition of instruction reordering optimization was implemented after Java 1.5, so the version before 1.5 is still unsafe, even if the volatile keyword is used.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325105537&siteId=291194637