Pacerier
Pacerier

Reputation: 89613

does final static automatically employ lazy instantiation?

the page at http://www.javaworld.com/javaworld/jw-04-2003/jw-0425-designpatterns.html?page=5 says that code like this:

public final static Singleton INSTANCE = new Singleton();

automatically employs lazy instantiation.

I want to verify if

1) all compilers do this, or is it that the compiler is free to do whatever it wishes to

2) and since c# does not have the "final" keyword, what's the best way to translate this into c# (and at the same time it should automatically employ lazy instantiation too)

Upvotes: 0

Views: 174

Answers (1)

pickypg
pickypg

Reputation: 22332

Yes. The static initializer is guaranteed to run before you are able to access that INSTANCE. There are two negatives with this approach:

  1. If an error occurs within the Singleton's construction, then the error is a little harder to debug ("Error in initializer").
  2. On first use of the class, that object will be instantiated. If you did the locking approach, then it would not be instantiated until it was needed. However, being that the example is a singleton, then this is not a problem at all, but it could be a drag on an unused, yet lazily instantiated piece of code elsewhere that is not a singleton.

The translation for C# is readonly instead of final.

In my opinion, this is still vastly preferable to the secondary approach (synchronized/locked, checked instantiation within the a static getter) because it does not require any synchronization code, which is faster, easier to read and just as easy to use.

Upvotes: 3

Related Questions