Should I override the default ExecutionContext?

前端 未结 3 1612
無奈伤痛
無奈伤痛 2020-12-23 14:45

When using futures in scala the default behaviour is to use the default Implicits.global execution context. It seems this defaults to making one thread available per proces

相关标签:
3条回答
  • 2020-12-23 15:17

    Yes, creating and using other execution contexts in you application is definitely a good idea.

    Execution contexts will modularize your concurrency model and isolate the different parts of your application, so that if something goes wrong in a part of your app, the other parts will be less impacted by this. To consider your example, you would have a different execution context for DB-specific operations and another one for say, processing of web requests.

    In this presentation by Jonas Boner this pattern is referred to as creating "Bulkheads" in your application for greater stability & fault tolerance.

    I must admit I haven't heard much about execution context usage by itself. However, I do see this principle applied in some frameworks. For example, Play will use different execution contexts for different types of jobs and they encourage you to split your tasks into different pools if necessary: Play Thread Pools

    The Akka middleware also suggests splitting your app into different contexts for the different concurrency zones in your application. They use the concept of Dispatcher which is an execution context on batteries.

    Also, most operators in the scala concurrency library require an execution context. This is by design to give you the flexibility you need when in modularizing your application concurrency-wise.

    0 讨论(0)
  • 2020-12-23 15:24

    The "correct" answer is that your methods that needs to use an ExecutionContext require an ExecutionContext in their signature, so you can supply ExecutionContext(s) from the "outside" to control execution at a higher level.

    0 讨论(0)
  • 2020-12-23 15:32

    Instead of thinking of it as overriding the default execution context, why not ask instead "Should I use multiple execution contexts for different things?" If that's the question, then my answer would be yes. Where I work, we use Akka. Within our app, we use the default Akka execution context for non blocking functionality. Then, because there is no good non blocking jdbc driver currently, all of our blocking SQL calls use a separate execution context, where we have a thread per connection approach. Keeping the main execution context (a fork join pool) free from blocking lead to a significant increase in throughput for us.

    I think it's perfectly ok to use multiple different execution contexts for different types of work within your system. It's worked well for us.

    0 讨论(0)
提交回复
热议问题