Java强制关闭阻塞线程_强制Java流尽早执行管道的一部分,以将阻塞任务提交给线程池...

我有一个我想要处理的对象列表,

Java8流API看起来是最干净和可读的方式.

但是我需要对这些对象执行的一些操作包括阻塞IO(比如读取数据库) – 所以我想将这些操作提交给有几十个线程的线程池.

起初我想过做一些事情:

myObjectList

.stream()

.filter(wrapPredicate(obj -> threadPoolExecutor.submit(

() -> longQuery(obj) // returns boolean

).get()) // wait for future & unwrap boolean

.map(filtered -> threadPoolExecutor.submit(

() -> anotherQuery(filtered) // returns Optional

))

.map(wrapFunction(Future::get))

.filter(Optional::isPresent)

.map(Optional::get)

.collect(toList());

wrapPredicate和wrapFunction仅用于检查异常重新抛出.

但是,很明显,对Future.get()的调用将阻塞流的线程,直到查询完成给定对象,并且流将在此之前不进行.因此,一次只处理一个对象,并且线程池没有意义.

我可以使用并行流,但是我需要希望默认的ForkJoinPool足够用于此.或者只是增加“java.util.concurrent.ForkJoinPool.common.parallelism”,但我不想为了那个流而改变整个应用程序的设置.我可以在自定义ForkJoinPool中创建流,但我看到it does not guarantee that level of parallelism.

所以我最终得到了类似的东西,只是为了保证在等待期货完成之前将所有需要的任务提交给threadPool:

myObjectList

.stream()

.map(obj -> Pair.of(obj, threadPoolExecutor.submit(

() -> longQuery(obj) // returns boolean

))

)

.collect(toList()).stream() // terminate stream to actually submit tasks to the pool

.filter(wrapPredicate(p -> p.getRight().get())) // wait & unwrap future after all tasks are submitted

.map(Pair::getLeft)

.map(filtered -> threadPoolExecutor.submit(

() -> anotherQuery(filtered) // returns Optional

))

.collect(toList()).stream() // terminate stream to actually submit tasks to the pool

.map(wrapFunction(Future::get)) // wait & unwrap futures after all submitted

.filter(Optional::isPresent)

.map(Optional::get)

.collect(toList());

有没有明显更好的方法来实现这一目标?

一种更优雅的方式告诉流“直到现在为流中的每个对象执行流水线步骤”,然后继续处理.collect(toList()).stream()以外的处理和更好的方法来过滤效果一个未来而不是将它打包到Apache Commons Pair中以便稍后过滤Pair :: getRight?或者对问题采取完全不同的方法?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值