5

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;
    }

}
ᴜsᴇʀ
  • 1,109
  • 2
  • 9
  • 23
  • 1
    Read [here](http://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java) about implementation. – alex2410 Sep 03 '15 at 09:05

3 Answers3

2

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;
    }

}
Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • @alex2410 This is just for sake of difference in case of final. Not the matter of thread safety. – Suresh Atta Sep 03 '15 at 09:03
  • @alex2410 Again this is not a solution. I gave the difference in first line it self. There is no in already implemented solutions. This is just to show the difference where `static final` and `static` make difference. – Suresh Atta Sep 03 '15 at 09:44
0

If you don't want to be lazy (and do lazy initialization), then you might want to make it final, because you could (INTENTIONALLY) do something like this :

class Sample {
   static Object o = new Object(); // o is not final. Hence can change.
    static{
     o = new Object();
     o = new Object();
    }
}

I would suggest Singleton using Enum instead of this.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
-2

People use only static to account for lazy initialization.

public class Singleton {

    private static Singleton instance = null;

    private Singleton() {
    }

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

}

This way, you don't need to always hold an instance, even if your application is not using it at all. Only create it the first time the application needs it.

Codebender
  • 14,221
  • 7
  • 48
  • 85
  • Thread safety also depends on the other fields of the object. And the OP's question was about being final or not... – Codebender Sep 03 '15 at 09:07