I have a singleton class:
public class School { private HashMap<String, String> students; private static School school; private School(){ students = new HashMap<String, String>(); } public static School getInstance(){ if(school == null){ school = new School(); } return school; }
As you can see above, in a single class, I have a students variable (a HashMap ), there are methods for adding and removing a student in a class.
In my application, there may be several threads using this School class for getInstance() , and then adding and removing a student. To make access ( especially access to the students instance ) thread safe , I am thinking of using the synchorized keyword for getInstanc() , for example:
public synchronized static School getInstance(){ if(school == null){ school = new School(); } return school; }
But I think that my trivial change can guarantee that in a multi-threaded environment only one School instance will be created. What else do I need to do to make it thread safe for accessing the students instance by multiple threads as well . Any good suggestion or comment is in dispute, thanks!
source share