Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton pattern: static or static final?

It is better to declare the instance of a Singleton as static or as static final?

See the following example:

static version

public class Singleton {

    private static Singleton instance = new Singleton();

    private Singleton() {
    }

    public static Singleton getInstance() {
        return instance;
    }

}

static final version

public class Singleton {

    private static final Singleton INSTANCE = new Singleton();

    private Singleton() {
    }

    public static Singleton getInstance() {
        return INSTANCE;
    }

}
like image 316
ᴜsᴇʀ Avatar asked Nov 22 '22 06:11

ᴜsᴇʀ


1 Answers

In your particular cases, there is no difference at all. And your second is already effectively final.

But

Keeping aside the fact that the below implementation is NOT thread safe, just showing the difference with respect to final.

In case of lazy initialization of your instance, you may feel the difference. Look lazy initialization.

public class Singleton {

    private static Singleton INSTANCE; /error

    private Singleton() {
    }

    public static Singleton getInstance() {
      if (INSTANCE ==null) {
         INSTANCE = new Singleton(); //error
      }
        return INSTANCE;
    }

}
like image 177
Suresh Atta Avatar answered Nov 23 '22 20:11

Suresh Atta