java - HashSet storing Singleton object twice -


i store singleton object through 10,000 threads in hashset (i.e. 10,000 times). surprisingly hashset can't recognize object singleton , stores same object instance 2 times. , sometimes, stores object once size() method returns value 2 or 3.

my singleton class is:-

public class singleton {    private singleton() {      system.out.println("singleton--- runs once");      }     private static class stagesingletonholder {      static singleton instance = new singleton();      }      public static singleton getinstance() {      return stagesingletonholder.instance;   }    } 

the runobject provides run method main class' threads:-

import java.util.hashset; import java.util.set;    public class runobject implements runnable{   singleton singleton;   public static set<singleton> set = new hashset<singleton>();     public void run(){        singleton = singleton.getinstance();       set.add(singleton);            }        public int numberofsingletons(){      for(singleton single:set){          system.out.println(single);          }      system.out.println("set size : "+set.size());     }   } 

my main class is:-

  public class mainobject {     public static void main(string[] args){    runobject runobject = null;    thread t;    int = 0;    while(i++ < 10000){     runobject = new runobject();     t = new thread(runobject);     t.start();     }    }  } 

here, in cases, same object stored more once. know singleton logic works correctly because constructor runs once. evident constructor printing statement once.

what reason of inconsistency?

hashset not thread safe. need synchronize adding or use appropriate concurrent collection storing singleton.


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -