I am reading about java singleton and I've met strange things.
I will refer to following artice as example(you can easy find more)
Author provides the following singleton:
public class ASingleton {
private static ASingleton instance = new ASingleton();
private ASingleton() {
}
public static ASingleton getInstance() {
return instance;
}
}
and comments:
Pros:
-Thread safety without synchronization
- Easy to implementCons:
- Early creation of resource that might not be used in the application.
-The client application can’t pass any argument, so we can’t reuse it.
For example, having a generic singleton class for database connection
where client application supplies database server properties.
I want to get clarification about Thread safety without synchronization point.
I've read concurrency in practice book and don't remember anything related with this.
I missed something or this clarification is not relevant?
Additionally I want to tell you that you can encounter the same singleton but field marked as static final
instead of just static
P.S.
I understand that I can read JMM and this one contains the answer but I am usual guy and I can't undertand this source.
According to securecoding.cert.org this is a valid pattern:
The point is: loading classes is a well defined operation. And executing static initializing code falls into the same category.
It is important to understand: JMM knowledge is only "required" when you go for the
static field
+ lazy init variant:Final
ly: thefinal
keyword should not affect this at all. Usingfinal
is much more about expressing your intent to declare a well, final thing - instead of one that gets potentially updated later on.