[英]Caching Futures and using as they complete
我想知道是否有一種方法可以緩存期貨以在完成時使用。 例如,我有一個主線程產生一個從輸入流中讀取的執行程序:
// pseudo code
while(true){
Callable task = new Callable({
// setup callable stuff here
byte[] call(){
return inputStream.readInBytes();
}
});
Future f = executors.submit(task);
byte[] b = f.get(); // blocks Uggh
// execute of b
process(b);
}
我想知道是否有辦法將期貨放入集合中,然后在完成時進行處理。
// pseudo code
while(true){
Callable task = new Callable({
// setup callable stuff here
byte[] call(){
return inputStream.readInBytes();
}
});
Future f = executors.submit(task);
futures.add(f);
// process bytes as they completed.
for(Future f: futures){
if(f.isDone()){ // this doesn't always return valid. It sometimes throws NPE's
b = f.get();
process (b);
}
}
}
我已經嘗試了第二段代碼,但是有時會拋出NPE-我假設正在剛啟動的線程上正在調用“ isDone”方法(猜測)。
有誰知道一種在期貨開始交易之前對其進行緩存的方法嗎? 現在,我的程序可以串行工作,但是我正在尋找優化和加速程序的方法。
謝謝
我不會使用Byte[]
而是使用byte[]
或可回收的緩沖區。
如果要在數據可用時對其進行處理,請在背景線程中進行處理。
/* loop */ {
futures.add(new Callable<Result>() {
// setup callable stuff here
Result call(){
byte[] bytes = inputStream.readInBytes();
return process(bytes);
}
});
}
// collect the results
for(Future<Result> f: futures){
Result result = g.get();
// do something single thread
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.