有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是kotlinx。共程。withContext`与Spring WebFlux一起使用安全吗?

想象一下,我有一个用Kotlin实现的Spring WebFlux控制器,看起来像这样:

@RestController
@RequestMapping("/api/foo")
class MyController {
  @GetMapping
  suspend fun getFoo(): FooResource {
    return withContext(Dispatchers.IO) {
      // fetch some resource with some expensive blocking IO call
    }
  }
}

按照我对WebFlux并发模型的理解,只有一个线程可用于处理请求,因此如果出于某种原因无法避免阻止IO调用,我需要以某种方式将其转移到另一个线程。kotlinx.coroutines.withContext助手应该正好做到这一点,而IO调度器是专门为这种用例设计的`我在几篇博客文章中看到过这种模式,所以这似乎是常识

然而,{}上的文档说:

This dispatcher shares threads with a Default dispatcher, so using withContext(Dispatchers.IO) { ... } does not lead to an actual switching to another thread — typically execution continues in the same thread. As a result of thread sharing, more than 64 (default parallelism) threads can be created (but not used) during operations over IO dispatcher.

因此,这让我想知道:如果WebFlux只使用一个“主线程”来处理请求,并且即使我使用withContext(Dispatchers.IO),阻塞IO仍可能发生在这个线程中:使用这种模式安全吗?如果不安全,我还应该做什么


共 (1) 个答案

  1. # 1 楼答案

    是的,它是安全的,你理解正确了

    您在这里提到的这篇文档只是讨论了在IODefault调度器之间切换时Dispatchers.IO的优化(这避免了上下文切换)

    Default/IO线程池以外的其他线程使用withContext(Dispatchers.IO)将正确(并且总是)将上下文切换到该IO线程池,根据需要启动新线程来处理阻塞IO,因此在您的情况下,这应该是一种方法