我正在實現Future<Collection<Integer>>
接口,以便在應用程序中的所有線程之間共享某些批量計算的結果。實現共享計算的未來接口
其實,我本打算只是把一類implemetnting Future<Collection<Integer>>
的實例爲ApplicationScope對象,以便任何其他線程其需要的結果只是從object
索要Future
並調用該方法get()
就可以了,所以用由另一個線程執行的計算。
我的問題是關於實施cancel
方法。現在,我會寫這樣的事情:
public class CustomerFutureImpl implements Future<Collection<Integer>>{
private Thread computationThread;
private boolean started;
private boolean cancelled;
private Collection<Integer> computationResult;
private boolean cancel(boolean mayInterruptIfRunning){
if(computationResult != null)
return false;
if(!started){
cancelled = true;
return true;
} else {
if(mayInterruptIfRunning)
computationThread.interrupt();
}
}
//The rest of the methods
}
但這種方法實現不滿足Future的文件,因爲我們需要在任何線程等待的結果扔CancellationException
(也稱爲get()
法) 。
我應該添加另一個字段,如private Collection<Thread> waitingForTheResultThreads;
,然後從Collection
中斷每個線程,捕獲中斷的異常,然後throw new CancellationException()
?
事情是,這樣的解決方案似乎對我來說有點奇怪......不知道這一點。
順便說一句,我沒有實際執行它。我只創建了少量冗長的接口,只有三個方法:'public T ensureResult();'如果它還沒有開始計算,並等待它完成,如果某個線程啓動它。方法'isStarted'和'done()'返回計算的狀態。 –
關於這樣的解決方案你會怎麼說? –
聽起來像一個更弱的'未來'。如果沒有更充分的理解你的目標,我不能說這是一個好的解決方案,但總的來說,我鼓勵重用而不是重新創建。 ['供應商'](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Supplier.html),'ListenableFuture',偶爾還有'AbstractFuture'(以及他們相關的工具類)應該做你需要的大部分事情。 – dimo414