静的メソッドとシングルトン クラスを含むコード サンプルがあります。
//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
}
}
これは、使用する最良の方法です。2 つのスレッドがメソッドの 1 つを呼び出すとどうなりますか? コレクションの処理中にデータが破損する可能性はありますか? 静的メソッドには共通メモリが割り当てられているため、2 つのスレッドが静的メソッドを呼び出すと、互いに影響しますか? シングルトンでは 1 つのインスタンスのみが作成されます。2 つのスレッドが単一のインスタンスでメソッドを呼び出すと、互いに影響しますか? これを理解するのを手伝ってください。ありがとうございました...