Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: excess synchronization

...

Code Block
bgColor#FFcccc
class MySingleton {
  private static MySingleton instance;

  protected MySingleton() {    
    instance = new MySingleton();
  }

  public static synchronized MySingleton getInstance() {    
    return instance;
  }
}

...

Code Block
bgColor#ccccff
class MySingleton {
  private static final MySingleton instance = new MySingleton();

  private MySingleton() {    
    // Private constructor prevents instantiation by untrusted callers
  }

  public static synchronized MySingleton getInstance() {    
    return instance;
  }
}

The MySingleton class need not be declared final because it has a private constructor.

(Note that the initialization of instance  is done when MySingleton  is loaded, consequently it is protected by the class's initialization lock. See the JLS s12.4.2 for more information.)

Noncompliant Code Example (Visibility across Threads)

...

Code that is outside the scope can create another instance of the singleton class even though the requirement was to use only the original instance. 

Because  Because a singleton instance is associated with the class loader that is used to load it, it is possible to have multiple instances of the same class in the Java Virtual Machine. This situation typically occurs in J2EE containers and applets. Technically, these instances are different classes that are independent of each other. Failure to protect against multiple instances of the singleton may or may not be insecure depending on the specific requirements of the program.

...

Tool
Version
Checker
Description
The Checker Framework

Include Page
The Checker Framework_V
The Checker Framework_V

Linear CheckerControl aliasing and prevent re-use (see Chapter 19)
Coverity7.5

SINGLETON_RACE
UNSAFE_LAZY_INIT
FB.LI_LAZY_INIT_UPDATE_STATIC
FB.LI_LAZY_INIT_STATIC

Implemented
Parasoft Jtest9.5

Include Page
Parasoft_V
Parasoft_V

CERT.MSC07TRS.ILIMake lazy initializations thread-safe

...