0

I am in between an implementation where I am planning to use static block inside static Inner class.
This implementation is being done as part of lazy initialization of a singleton class.

I am not able to find any information on google if it is advisable or a good practice to do so?

Any suggestions are welcome.

public class MySingleton {

    private MySingleton() {
    }

    private static class InnerMySingleton {
        private static volatile MySingleton mysingleton;
        static {
            mysingleton = new MySingleton();
        }
    }

    public static MySingleton getInstance() {
        return MySingleton.InnerMySingleton.mysingleton;
    }
}
ernest_k
  • 39,584
  • 5
  • 45
  • 86
  • 1
    this is [Initialization-on-demand holder idiom](https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom) and you could just do `private static final MySingleton mysingleton = new MySingleton();` – michalk Nov 27 '19 at 10:28
  • @michalk Well its a complex object to create this is not the actual code but a basic prototype. There are lot of steps involved in creating the actual object. – ANKIT SRIVASTAVA Nov 27 '19 at 10:30

1 Answers1

3

First of all, you could just go:

private static volatile MySingleton mysingleton = new MySingleton();

the static block doesn't add anything useful here. And in case it is more complicated, then don't use a static block, but

private static MySingleton makeSingleton() { ...

for example. Meaning: prefer a method over a nameless block (because that method can have a name that tells the reader what the method is supposed to do). static just says, well, "what follows happens static".

Second: when in doubt, try to write less code. There is really no advantage of static blocks for simple assignments. See here for some reasoning.

Beyond that, you might want to study the CERT on double locking for example. There are myriads of ways to go about this.

GhostCat
  • 127,190
  • 21
  • 146
  • 218
  • Sorry my bad i didn't mentioned in the actual question that the code snippet provided is just an example of how i am using the static block in my singleton class. I have edited the question. There are multiple steps involved in creating the object and hence a single line declaration cannot be used – ANKIT SRIVASTAVA Nov 27 '19 at 10:33