javaconcurrencysingletonstatic-methodssingleton-methods

static method vs singleton methods in multithreaded environment


I have a code sample with static methods and singleton class

//code with static methods
public class DataManager{
  public static Object getDataObject(){
     HashMap map = new HashMap();
     //Some processing in collections
     //retrieval of data
  }
  public static void writeData(Object o){
     HashMap map = new HashMap();
     //Some processing in collections
     //writing data
  }
}
//code with singleton
public class DataManager{
   private static DataManager instance;
   private DataManager(){
   }
   public static DataManager getInstance(){
     if(instance == null){
        synchronized(DataManager.class){
          if(instance == null){
              instance = new DataManager();
          }
       }
    }
    return instance;
  }
  public Object getDataObject(){
     HashMap map = new HashMap();
     //Some processing in collections
     //retrieval of data
  }
  public writeData(Object o){
     HashMap map = new HashMap();
     //Some processing in collections
     //writing data
  }
}

Which is the best way to use. What happens when 2 threads calls one of my methods? Is there any way my data could get corrupt while processing on collections? static method has common memory allocated for it, so when 2 threads calls a static method will it affect each other? in singleton only one instance is created, if 2 threads calls a method with a single instance will it affect each other? Please help to understand this. Thank you...


Solution

  • From my understanding on multithreading, it is the shared object which will be accessed by multiple threads.

    So in both of your program, the map object is the shared instance which will be accessed by multiple threads. So you should synchronize map object inorder to be thread safe.

    Singleton or Static has no way related to this