Prior to Java 5, the Synchronized
method and block Synchronization
has a lot of issues and were failing in multiple scenarios in multi-threaded environments. So Bill Pugh suggested using static inner class to create Singleton
classes.
The static inner classes
will only get loaded in JVM
memory when the getInstance
method is called which makes it lazy-loaded
. The static inner
class will be invoked sequentially in JVM
ie non-concurrent
, so these are not required to be Synchronized
, in a multi-threaded
or concurrent
environment, the threads will invoke the static class in order hence don't need external Synchronization
which makes it thread-safe
.
package org.wesome.dsalgo.design.pattern.singleton;
public class Apple {
public Apple() {
System.out.println("Apple default constructor");
}
public static void favoriteFruitUtilityFunc() {
System.out.println("Apple is my favorite fruit.");
}
private static class BillPughSingletonClass {
static Apple appleInstance = new Apple();
}
public static Apple getAppleInstance() {
System.out.println("Apple getAppleInstance");
return BillPughSingletonClass.appleInstance;
}
}
package org.wesome.dsalgo.design.pattern.singleton;
public class SingletonClass {
public static void main(String[] args) {
Apple.favoriteFruitUtilityFunc();
System.out.println(Apple.getAppleInstance());
}
}
plugins {
id 'java'
id "io.freefair.lombok" version "6.4.1"
}
group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}
test {
useJUnitPlatform()
}