2014-10-20 37 views
0

在我的代碼中我有一個對象叫做DataLogger。正如名稱所說,它負責將數據記錄到文件中。實現一個基本的DataLogger

類的骨架看起來像這樣:

class DataLogger { 

    private BufferedWriter mFileWriter = ... 
    private boolean mRunning = false; 

    //constructor 
    public DataLogger() { 
    //init stuff 
    } 

    public void onEvent(..) { 
    //... 
    if(mRunning) { 
     mFileWriter.write(...); 
    } 
    /... 
    } 

    public void start() { 
    //startdata logging 
    mRunning = true; 
    } 

    public void stop() { 
    //stop data logging 
    mRunning = false; 
    //closing File writer etc. 
    } 
} 

所以對象在onEvent方法接收Events。每次新事件進入時,數據都將被記錄到文件中。數據記錄器應該使用start()方法啓動,並使用stop()方法停止。我用這段代碼看到的問題是,如果DataLogger的客戶端/調用者調用stop(),則可能是事件剛剛在同一時刻到達,然後會被記錄下來,儘管用戶之前調用了stop()。如果數據流已經關閉,這甚至會導致崩潰。我想我需要添加一些synchornization /鎖定代碼在這裏是這樣嗎?什麼是擴展我的代碼的最佳方式?

回答

1

最直接的解決方案是同步onEvent()和stop()。這樣,只有兩種方法中的一種可以同時被調用,解決了你最初的問題。

public void onEvent(..) { 
public void start() { 
public void stop() { 

成爲

public synchronized void onEvent(..) { 
public synchronized void start() { 
public synchronized void stop() {