2016-06-07 49 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'来处理事件。但是,那么它开始变得复杂:) –

相关问题