2014-03-19 27 views
3

我創建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的列表是空的,我不知道是什麼原因,如果任何機構知道的比幫助我 在此先感謝

+0

那麼,我的第一個想法是,你的工廠方法不是線程安全的,所以你不能保證你的對象是一個單身。 – Aurand

+0

@Aurand請給我一些提示我沒有得到,因爲我從來沒有在線程中工作,我沒有使用任何線程方法 –

+0

@RishiDwivedi你在調用SqlInsertPoint.givePoint之前調用Exp.setPoint嗎? 如果不是,那麼這是你的問題。 Singleton不會自動將數據保存在磁盤上。所以每次Singleton對象被丟棄時(每次程序終止時),都會丟失它的狀態以及它在內存中保存的信息。如果您需要保存數據,則在程序終止之前需要將其保存到磁盤(使用數據庫,序列化,等等..)。 – m1o2

回答

0

什麼是錯的代碼?在main中,您獲得了PointCalculate的一個實例,請勿將任何點加入,並將其傳遞給givePoint方法。既然你沒有填充HashMap,它應該是空的。

在單獨的筆記中,靜態單身人士很難找到正確的,一般應該避免(couplegood reasons)。在您的具體情況下,不僅PointCalculate類不是線程安全的,但它也暴露calPoint到全世界。所以,任何人都可以運行下面的代碼,基本上覆蓋你的實例。

PointCalculate.getInstance()。calPoint = new HashMap();

相關問題