我創建singleton類並在不同的類中使用此類對象此代碼在eclipse中正常工作 但是當我使runnable jar比使用空hashmap列表時我不知道爲什麼我的代碼...Singleton對象在jar中破壞但在eclipse中工作
我的單身類
public class PointCalculate {
public HashMap<String, Float> calPoint;
private static PointCalculate instance;
private PointCalculate(){
calPoint = new HashMap<String, Float>();
}
public static PointCalculate getInstance(){
if(instance==null){
instance = new PointCalculate();
}
return instance;
}
public void calculatePoint(String uid ,float point){
Float ps = instance.calPoint.get(uid);
if(ps==null) {
ps = point;
instance.calPoint.put(uid, ps);
}
else {
ps = point+ps.floatValue();
instance.calPoint.put(uid, ps);
}
}
}
,我從下面這個類傳遞價值....
public class Exp {
public void setpoint(){
PointCalculate obj = PointCalculate.getInstance();
obj.calculatePoint(rowkey, point);//rowkey and point come from file.....
}
}
現在我路過的HashMap .. ..
public static void main(String args[]) throws Exception {
PointCalculate obj = PointCalculate.getInstance();
SqlInsertPoint.givePoint(obj.calPoint);
}
但SqlInsertPoint.givePoint()HashMap的列表是空的,我不知道是什麼原因,如果任何機構知道的比幫助我 在此先感謝
那麼,我的第一個想法是,你的工廠方法不是線程安全的,所以你不能保證你的對象是一個單身。 – Aurand
@Aurand請給我一些提示我沒有得到,因爲我從來沒有在線程中工作,我沒有使用任何線程方法 –
@RishiDwivedi你在調用SqlInsertPoint.givePoint之前調用Exp.setPoint嗎? 如果不是,那麼這是你的問題。 Singleton不會自動將數據保存在磁盤上。所以每次Singleton對象被丟棄時(每次程序終止時),都會丟失它的狀態以及它在內存中保存的信息。如果您需要保存數據,則在程序終止之前需要將其保存到磁盤(使用數據庫,序列化,等等..)。 – m1o2