是否在单线程上执行期货? (Scala) [英] Are Futures executed on a single thread? (Scala)

查看:105
本文介绍了是否在单线程上执行期货? (Scala)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Scala中使用默认的隐式执行上下文,每个新的未来将在单个专用线程上计算,还是将计算分割并分布到线程池中的多个线程?



我不知道这是否有帮助,这个问题的背景是,我想使用HtmlUnit API执行多个并发操作。为此,我将每个新的WebClient实例包装在一个未来。唯一的问题是,WebClient类不是线程安全的,所以我担心它可能分解并发送到不同的线程。

解决方案

一个未来在单个线程上执行。几个期货可能在几个线程上执行。所以,没有比将来可以同时占据一个线程。



它是如何工作的?当你创建一个Future时,它意味着你已经将任务提交到线程池 - 这一个任务不能被隐式并行化,因此它只在一个线程上执行。提交到池的一个或多个任务被放入池的队列,因此执行器逐个从该队列中取出任务,并在某些随机(或故意)选择的线程上运行每个任务。



关于共享对象 - 为期货之间共享的对象执行操作的唯一方法是使用 Executors。 newFixedThreadPool(1),它将只使用一个线程的整个池。另一个解决方案 - 是为每一个未来克隆这样的对象。使用actors(使你的共享对象成为一个actor的状态)应该是最好的选择。



如果你每次使用一个对象 - 一切都很好。 b
$ b

注意:未来的处理程序,如 Future {...} .map(handler)可能在未来的线程中执行但它实际上创建了另一个 Future 以获得结果。与 flatMap 。更准确地说,他们使用 onComplete ,创建 CallbackRunnable 在旧的未来成功后启动处理程序回调只是完成新创建的未来,所以仍然每个未来不超过一个线程


Using the default implicit execution context in Scala, will each new future be computed on a single, dedicated thread or will the computation be divided up and distributed to multiple threads in the thread pool?

I don't know if this helps, the background to this question is that I want to perform multiple concurrent operations using the HtmlUnit API. To do this, I would wrap each new WebClient instance in a Future. The only problem is that the WebClient class is not thread safe, so I'm worried that it might broken up and sent to different threads.

解决方案

One future is executed on a single thread. Several futures might be executed on several threads. So, no more than on future can occupy one thread simultaniously.

How it works? When you create a Future it means that you've submitted task to your thread-pool - this one task can't be implicitly parallelized so it's executed on one thread only. One or several tasks submitted to the pool are being put into pool's queue, so executor takes tasks from that queue one-by-one and run each on some randomly (or intentionally) chosen thread. So several Futures may get to several threads.

About shared object - the only way to execute operations safely for object shared between futures is using Executors.newFixedThreadPool(1), it will use only one thread for the whole pool. Another solution - is to clone such object for every future. Using actors (make your shared object an actor's state) should be the best option.

If you use one object per future - everything should be fine.

Note: The future's handler, like Future{ ... }.map(handler) may be executed in different thread than the future itself, but it actually creates another Future to obtain a result. Same for flatMap. More precisely, they use onComplete which creates CallbackRunnable to launch handler (possible in different thread) after old future's success - this callback just completes newely created future, so still "no more than one thread per future"

这篇关于是否在单线程上执行期货? (Scala)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆