2016-06-07 48 views
0

比方說,我有一個ExecutorService(.newFixedThreadPool(2))需要一系列請求。爲了簡單起見,它們只是:{ String url }在運行未完成任務之前篩選ExecutorService ThreadPool

假設我按照該順序的網址爲[ aaa, bbb, ccc, aaa, ddd, aaa, ... ]。 (是的,aaa被重複多次)

那些url事件異步進來,所以它們都會在到達時提交到ExecutorService

有沒有辦法讓ExecutorService在允許下一個未決項目運行前檢查一個條件?例如。檢查未來的未決結果是否包含'aaa',如果是,則丟棄它,以便只觸發最近的結果。

我想出了一個hacky的方式,通過將url請求映射到時間戳並讓線程死亡,如果他們的時間戳不再匹配。但是,這具有ExecutorService仍然運行所有請求導致到最新的結果,如果連續提交很多請求,這可能會很重。

任何意見將不勝感激...謝謝!

回答

1

只是一些頭腦風暴,我希望能幫助你:

約維持「URL事件隊列」什麼是事件進來,再有一種類型的管理「URL事件隊列「隊列處理器線程」的「並根據需要使用正確的」url事件「啓動ExecutorService線程?

所以,如果我正確地跟着你,你的解決方案是
1)事件進來
2)揭開序幕線程

我的建議
1)事件到來時,把它放在一個隊列
2)「隊列處理器線程」看到隊列中有東西,根據需要進行一些隊列清理等,並將下一個「url事件」傳遞給ExecutorService。

你說:我已經通過映射URL請求到 時間戳和其如果它們的時間戳不再 匹配線程死想出了一個哈克的方式

。但是,這具有ExecutorService仍然 運行所有請求導致最新的結果,如果連續提交很多請求,則可能會導致嚴重的 。

嗯,有趣。請記住,創建線程很昂貴。你如何實例化你的ExecutorService - 因爲它不應該有必要創建新的線程。也許你剛剛說的ExecutorService的開銷,看着所有的事件中的每個線程都很貴,但我只想說,這在任何情況下:

如:

int threadPoolSize = Runtime.getRuntime().availableProcessors(); 
ExecutorService threadPool = Executors.newFixedThreadPool(threadPoolSize); 

剛的Javadoc該方法出於興趣:

/** 
* Creates a thread pool that reuses a fixed number of threads 
* operating off a shared unbounded queue. At any point, at most 
* {@code nThreads} threads will be active processing tasks. 
* If additional tasks are submitted when all threads are active, 
* they will wait in the queue until a thread is available. 
* If any thread terminates due to a failure during execution 
* prior to shutdown, a new one will take its place if needed to 
* execute subsequent tasks. The threads in the pool will exist 
* until it is explicitly {@link ExecutorService#shutdown shutdown}. 
* 
* @param nThreads the number of threads in the pool 
* @return the newly created thread pool 
* @throws IllegalArgumentException if {@code nThreads <= 0} 
*/ 
public static ExecutorService newFixedThreadPool(int nThreads) { 

我喜歡排隊模型:)記住,現在我們只是有一個線程,看起來在「URL事件隊列」。這聽起來像在你的例子中,ExecutorService中的每個線程都不得不查看隊列並確定它是否需要處理它的「url事件」。

希望這有助於...

+0

我還沒有在一段時間用'Executors'工作,也許也看看'執行人#newCachedThreadPool()'等等 - 我只是不能給任何意見另一個'Executors'構造函數和'ExecutorService'子類關閉了我的頭頂... –

+0

非常感謝這麼詳細的回覆,我真的很感激它!它實際上不僅僅是url地圖,因爲它實際上必須確保該請求對於特定視圖,url,圖像增強標識以及提交它的時間戳是有效的。這是一個https://github.com/mattsilber/imageloader我實際上正在考慮擴展ThreadPoolExecutor在此刻從beforeExecute隊列中刪除項目,以避免問題,但隊列和未決項目之間的包裝可以很好地工作......感謝您的建議! – Guardanis

+0

我的榮幸!也許別人回答一些有用的見解。我想我的方法會遇到問題,如果「隊列處理線程」無法將足夠快的「url事件」傳遞給其他線程。我想可以有一個'ExecutorService'來管理隊列,然後是另一個'ExecutorService'來處理事件。但是,那麼它開始變得複雜:) –

相關問題