Singleton#
Eager initialization#
1class Resource {
2 private static final Resource INSTANCE = new Resource();
3
4 private Resource() {}
5
6 public static Resource getInstance() {
7 return INSTANCE;
8 }
9}
Thread-safe.
Instance is created even if it’s never used.
Lazy initialization#
Double checked locking#
1public class Resource {
2 private volatile Resource instance = null;
3
4 private Resource() {}
5
6 public static Resource getInstance() {
7 if (instance == null) { // First check
8 synchronized (this) {
9 if (instance == null) { // Second check
10 instance = new Instance();
11 }
12 }
13 }
14 return instance;
15 }
16}
Concise#
1public class Resource {
2 private Resource() {}
3
4 private static class Holder {
5 static final Resource INSTANCE = new Resource();
6 }
7
8 public static Resource getInstance() {
9 return Holder.INSTANCE;
10 }
11}
On calling Holder.INSTANCE
only creates resource using new Resource()
.
Enum#
enum Resource {
INSTANCE;
Resource() {
// initialization
}
// instance methods
}
References#
https://rules.sonarsource.com/java/RSPEC-6548/