I have created a main class and ran a thread for 10000 tines each time it hits run method it will call l SingleTon.getInstance method and adds hashcode to a list but i am wondering why iam getting
output like this even though the getinstance method of SingleTon is synchronized
[1388889817, 1388889817, 1388889817, 1388889817, 1388889817, 1388889817, 1388889817, 1388889817, 1388889817, 1388889817, null, ...so on
here the unique hashcode which iam able to see
[null, 1388889817] why null is there only the hashcode 1388889817 should be present.
public class InsSingleton implements Runnable {
public List<Integer> list = new ArrayList<>();
public int cnt = 0;
// Adding hashcode values to a list
@Override
public void run() {
list.add(SingleTon.getInstance().hashCode());
}
}
public static void main(String[] args) throws InterruptedException {
List<Integer> list = new ArrayList<>();
InsSingleton insSingleton = new InsSingleton();
for (int i = 0; i < 10000; i++) {
new Thread(insSingleton).start();
}
list = insSingleton.list;
Set<Integer> set = new HashSet<>();
Set<Integer> set1 = new HashSet<>();
for (int i = 0; i < list.size(); i++) {
// checking what hashcode are added in list
if (set.add(list.get(i)))
set1.add(list.get(i));
}
// printing the hashcodes
System.out.println(list);
System.out.println(set1);
}
public class SingleTon {
private static SingleTon singleTon = null;
//private constructor
private SingleTon() {
}
//synchronized method
public static synchronized SingleTon getInstance() {
if (singleTon == null) {
singleTon = new SingleTon();
}
return singleTon;
}
}