1

If I create a singleton object using static final, then will it be thread safe? Here is the example code.

public class StaticSingleton {
    private static final StaticSingleton instance = new StaticSingleton();

    private StaticSingleton() {
    }

    public static StaticSingleton GetInstance() {
        return instance;
    }
}
Gayan Mettananda
  • 1,498
  • 14
  • 21
Maheraj
  • 101
  • 2
  • 2
  • 7
  • It doesn't make the singleton object itself *thread-safe* if that's what you mean, just the initialisation (unless you do something dodgy within). – Tom Hawtin - tackline Dec 08 '18 at 12:20
  • Also, it is apparently very fast, when comparing with all other non-static non-final solutions: http://literatejava.com/jvm/fastest-threadsafe-singleton-jvm/ – ygor Dec 08 '18 at 14:01

1 Answers1

0

Yea, That's eager as you said and also thread safe. take a look in this example:

classFoo {
    private static class HelperHolder{
        public static final Helper helper= new Helper();
    }

    public static Helper getHelper() {
        return HelperHolder.helper;
    }
}

This is not eager so our helper object will be created only when you will need him (inner classes are not loaded until they are referenced) - lazy :)

Elad Aharon
  • 405
  • 2
  • 18
  • 1
    Usually pointless as you probably aren't going to initialise `Foo` without almost immediately calling `getHelper`, not unless `Foo` is a big mess of a class. – Tom Hawtin - tackline Dec 08 '18 at 12:21