import java.util.*;
public class Singleton {
private static volatile Singleton singleton;
private Singleton() { }
public synchronized Singleton getInstance() {
// TODO: 3/29/20 Synchronize this
if(singleton == null) {
System.out.println("created singleton");
singleton = new Singleton();
}
return singleton;
}
public static void main(String[] args) {
// TODO: 3/29/20 Simulate the scenario when multiple threads call the method getInstance
List list = new ArrayList<>();
Singleton s = new Singleton();
for(int i = 0; i < 20; i++) {
list.add(new Thread(new Runnable() {
@Override
public void run() {
s.getInstance();
}
}));
}
for(int i = 0; i < 20; i++) {
list.get(i).start();
}
for(int i = 0; i < 20; i++) {
try {
list.get(i).join();
}
catch (InterruptedException e) {
System.out.println(e);
}
}
}
}