On Sat, 18 Sep 2021 23:08:21 GMT, Sergey Bylokhov <[email protected]> wrote:

>> The method `FontManagerFactory.getInstance()` is updated to use DLC.
>> 
>> I used synchronization on FontManagerFactory.class in the first check to be 
>> consistent with the previous behavior where synchronization was on the 
>> `FontManagerFactory.getInstance()` method.
>> 
>> What about to use a static nested class singleton? It could look like:
>> 
>> public final class FontManagerFactory {
>> 
>>     public static FontManager getInstance() {
>>         return FontManagerHolder.instance;
>>     }
>> 
>>     private static class FontManagerHolder {
>>         private static final FontManager instance = 
>> PlatformFontInfo.createFontManager();
>>     }
>> }
>
> The SunFontManager constructor and its subclasses seem too big, and 
> potentially throw some exceptions and this will ruin the holder idiom since 
> all subsequent calls to this method will fail.

I wrote a simple example which uses DLC and lazy initialization holder class 
idioms. The FontManager is only created when it is accessed the first time via 
the getInstance() method in both cases and they both fail if an exception is 
thrown during the class initialization. Are there special restrictions on the 
class loading time in holder idiom?

public class FontManagerFactory {

    private static volatile FontManager instance;

    public static FontManager getInstanceDLC() {

        FontManager result = instance;
        if (result == null) {
            synchronized (FontManagerFactory.class) {
                result = instance;
                if (result == null) {
                    instance = result = new FontManager("One", "Two", "Three");
                }
            }
        }
        return result;
    }

    public static FontManager getInstanceHolder() {
        return FontManagerHolder.instance;
    }


    public static void main(String[] args) {
        String lazyInitializationIdiom = args[0];
        System.out.printf("Use lazy initialization idiom: %s%n", 
lazyInitializationIdiom);
        if ("DLC".equals(args[0])) {
            System.out.printf("DLC FontManager instance: %s%n", 
getInstanceDLC());
        } else if ("Holder".equals(args[0])) {
            System.out.printf("Lazy Initialization Holder FontManager instance: 
%s%n", getInstanceHolder());
        }
    }

    private static class FontManagerHolder {
        private static final FontManager instance = new FontManager("One", 
"Two", "Three");
    }
}

class FontManager {
    public FontManager(String... args) {
        System.out.println(args[5]);
    }
}

-------------

PR: https://git.openjdk.java.net/jdk/pull/5517

Reply via email to