DCL懶載入單例模式

lang20150928發表於2020-11-27
public class TomcatURLStreamHandlerFactory implements URLStreamHandlerFactory {
    // Singleton instance
    private static volatile TomcatURLStreamHandlerFactory instance = null;

    /**
     * Obtain a reference to the singleton instance. It is recommended that
     * callers check the value of {@link #isRegistered()} before using the
     * returned instance.
     *
     * @return A reference to the singleton instance
     */
    public static TomcatURLStreamHandlerFactory getInstance() {
        getInstanceInternal(true);
        return instance;
    }

    private static TomcatURLStreamHandlerFactory getInstanceInternal(boolean register) {
        // Double checked locking. OK because instance is volatile.
        if (instance == null) {
            synchronized (TomcatURLStreamHandlerFactory.class) {
                if (instance == null) {
                    instance = new TomcatURLStreamHandlerFactory(register);
                }
            }
        }
        return instance;
    }
}    

又比如

public class DefaultConversionService extends GenericConversionService{

   private static volatile DefaultConversionService sharedInstance;
   
   	/**
	 * Return a shared default {@code ConversionService} instance,
	 * lazily building it once needed.
	 * <p><b>NOTE:</b> We highly recommend constructing individual
	 * {@code ConversionService} instances for customization purposes.
	 * This accessor is only meant as a fallback for code paths which
	 * need simple type coercion but cannot access a longer-lived
	 * {@code ConversionService} instance any other way.
	 * @return the shared {@code ConversionService} instance (never {@code null})
	 * @since 4.3.5
	 */
	public static ConversionService getSharedInstance() {
		if (sharedInstance == null) {
			synchronized (DefaultConversionService.class) {
				if (sharedInstance == null) {
					sharedInstance = new DefaultConversionService();
				}
			}
		}
		return sharedInstance;
	}
}

相關文章