Singleton by enum

I was interested to learn about singleton in enum and performance.

When we have a multi-threaded environment, we must synchronize the moment when an instance is created.

We can just use a synchronized mod for a function called getInstance () that instantiates something like this:

public synchronized Singleton getInstance(){
    if(instance == null){
        instance = new Singleton();
    }
    return instance;
}

This is a lazy implementation, this is good for me. But the synchronized method is slow. We can use double locking to make it faster.

How about the listing? When we implement singleton as enum, a singleton instance will be created as the first use. Next use, return the current instance.

How it works? When we want to get an existing instance, is there an implicit synchronized method that is slow? Or is a double lock implemented?

+4
source share
3 answers

Enum is thread safe and is also the recommended way to implement Singleton.

However, the enumeration is not lazily loaded. If you want a lightweight singleton loaded, you can use the Holder template (which is also thread safe):

class LazySingleton {

    private LazySingleton() {}

    private static class SingletonHelper{
        private static final LazySingleton INSTANCE = new LazySingleton();
    }

    public static LazySingleton getInstance(){
        return SingletonHelper.INSTANCE;
    }
}
+3
source

No lazy initialization with enum. It will simply create an instance when the class loads.

When we implement singleton as enum, a singleton instance will be created as the first use.

, " ".

, , :

private static final Singleton instance = new Singleton();

public static Singleton getInstance() {
    return instance;
}
+1

enum , ,

static final Singleton instance = new Singleton();

static final Singleton instance;
static {
    instance = new Singleton();
}

- , JVM JVM:

Java , , .... Java .

...

C LC. C LC Java.

...

, Java-, , JVM . :

, 1 ( 4/5), , , , , - , , , , .

This, of course, is an important point in this implementation of the singleton pattern, that for subsequent access to the field static final, blocking is not required. Since all classes go from uninitialized to initialized state exactly once, and it affects every operation (including all other possibilities for implementing a singleton pattern), you can expect each JVM to do this fundamental optimization. Even if a particular JVM does not, the field static finalwill be the fastest lazy implementation of a single shell on this virtual machine ...

+1
source

Source: https://habr.com/ru/post/1689873/


All Articles