- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
Kotlin协程和非阻塞I/O有什么关系?一个暗示另一个吗?如果我使用阻塞 I/O 会怎样?这对性能有何影响?
最佳答案
协程旨在包含非阻塞(即 CPU 绑定(bind))代码。这就是为什么默认协程调度程序 – Dispatchers.Default – 共有 max(2, num_of_cpus)
线程来执行分派(dispatch)的协程。例如,默认情况下,一个高度并发的程序(例如在具有 2 个 CPU 的计算机中运行的 Web 服务器)的计算能力会降低 50%,而线程会阻塞等待 I/O 在协程中完成。
非阻塞 I/O 不是协程的特性。协程只是提供了一个更简单的编程模型,由暂停函数组成,而不是难以阅读CompletableFuture<T> Java 中的延续,以及 structured concurrency以及其他概念。
要了解协程和非阻塞 I/O 如何一起工作,这里有一个实际示例:
server.js:接收请求并返回响应的简单 Node.js HTTP 服务器 ~5s
之后。
const { createServer } = require("http");
let reqCount = 0;
const server = createServer(async (req, res) => {
const { method, url } = req;
const reqNumber = ++reqCount;
console.log(`${new Date().toISOString()} [${reqNumber}] ${method} ${url}`);
await new Promise((resolve) => setTimeout(resolve, 5000));
res.end("Hello!\n");
console.log(`${new Date().toISOString()} [${reqNumber}] done!`);
});
server.listen(8080);
console.log("Server started!");
main.kt:使用三种实现向 Node.js 服务器发送 128 个 HTTP 请求:
1. withJdkClientBlocking()
: 调用 JDK11 java.net.http.HttpClient在 Dispatchers.IO 调度的协程中阻塞 I/O 方法.
import java.net.URI
import java.net.http.HttpClient as JDK11HttpClient
import java.net.http.HttpRequest as JDK11HttpRequest
import java.net.http.HttpResponse as JDK11HttpResponse
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
fun withJdkClientBlocking() {
println("Running with JDK11 client using blocking send()")
val client = JDK11HttpClient.newHttpClient()
runExample {
// Sometimes you can't avoid coroutines with blocking I/O methods.
// These must be always be dispatched by Dispatchers.IO.
withContext(Dispatchers.IO) {
// Kotlin compiler warns this is a blocking I/O method.
val response = client.send(
JDK11HttpRequest.newBuilder(URI("http://localhost:8080")).build(),
JDK11HttpResponse.BodyHandlers.ofString()
)
// Return status code.
response.statusCode()
}
}
}
2. withJdkClientNonBlocking()
: 调用 JDK11 java.net.HttpClient
非阻塞 I/O 方法。这些方法返回 CompletableFuture<T>
使用 CompletionStage<T>.await() 使用其结果来自 kotlinx-coroutines-jdk8 的互操作性扩展功能.即使 I/O 不阻塞任何线程,异步请求/响应编码/解码在 Java Executor 上运行,因此该示例使用单线程执行器来说明由于非阻塞 I/O,单线程如何处理许多并发请求。
import java.net.URI
import java.net.http.HttpClient as JDK11HttpClient
import java.net.http.HttpRequest as JDK11HttpRequest
import java.net.http.HttpResponse as JDK11HttpResponse
import java.util.concurrent.Executors
import kotlinx.coroutines.future.await
fun withJdkClientNonBlocking() {
println("Running with JDK11 client using non-blocking sendAsync()")
val httpExecutor = Executors.newSingleThreadExecutor()
val client = JDK11HttpClient.newBuilder().executor(httpExecutor).build()
try {
runExample {
// We use `.await()` for interoperability with `CompletableFuture`.
val response = client.sendAsync(
JDK11HttpRequest.newBuilder(URI("http://localhost:8080")).build(),
JDK11HttpResponse.BodyHandlers.ofString()
).await()
// Return status code.
response.statusCode()
}
} finally {
httpExecutor.shutdown()
}
}
3. withKtorHttpClient()
用途 Ktor ,一个使用 Kotlin 和协程编写的非阻塞 I/O HTTP 客户端。
import io.ktor.client.engine.cio.CIO
import io.ktor.client.HttpClient as KtorClient
import io.ktor.client.request.get
import io.ktor.client.statement.HttpResponse as KtorHttpResponse
fun withKtorHttpClient() {
println("Running with Ktor client")
// Non-blocking I/O does not imply unlimited connections to a host.
// You are still limited by the number of ephemeral ports (an other limits like file descriptors).
// With no configurable thread limit, you can configure the max number of connections.
// Note that HTTP/2 allows concurrent requests with a single connection.
KtorClient(CIO) { engine { maxConnectionsCount = 128 } }.use { client ->
runExample {
// KtorClient.get() is a suspend fun, so suspension is implicit here
val response = client.get<KtorHttpResponse>("http://localhost:8080")
// Return status code.
response.status.value
}
}
}
综合起来:
import kotlin.system.measureTimeMillis
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.runBlocking
fun runExample(block: suspend () -> Int) {
var successCount = 0
var failCount = 0
Executors.newSingleThreadExecutor().asCoroutineDispatcher().use { dispatcher ->
measureTimeMillis {
runBlocking(dispatcher) {
val responses = mutableListOf<Deferred<Int>>()
repeat(128) { responses += async { block() } }
responses.awaitAll().forEach {
if (it in 200..399) {
++successCount
} else {
++failCount
}
}
}
}.also {
println("Successfully sent ${success + fail} requests in ${it}ms: $successCount were successful and $failCount failed.")
}
}
}
fun main() {
withJdkClientBlocking()
withJdkClientNonBlocking()
withKtorHttpClient()
}
示例运行:
main.kt(使用 # comments
进行说明)
# There were ~6,454ms of overhead in this execution
Running with JDK11 client using blocking send()
Successfully sent 128 requests in 16454ms: 128 were successful and 0 failed.
# There were ~203ms of overhead in this execution
Running with JDK11 client using non-blocking sendAsync()
Successfully sent 128 requests in 5203ms: 128 were successful and 0 failed.
# There were ~862ms of overhead in this execution
Running with Ktor client
Successfully sent 128 requests in 5862ms: 128 were successful and 0 failed.
server.js(使用 # comments
进行说明)
# These are the requests from JDK11's HttpClient blocking I/O.
# Notice how we only receive 64 requests at a time.
# This is because Dispatchers.IO has a limit of 64 threads by default, so main.kt can't send anymore requests until those are done and the Dispatchers.IO threads are released.
2022-07-24T17:59:29.107Z [1] GET /
(...)
2022-07-24T17:59:29.218Z [64] GET /
2022-07-24T17:59:34.124Z [1] done!
(...)
2022-07-24T17:59:34.219Z [64] done!
2022-07-24T17:59:35.618Z [65] GET /
(...)
2022-07-24T17:59:35.653Z [128] GET /
2022-07-24T17:59:40.624Z [65] done!
(...)
2022-07-24T17:59:40.655Z [128] done!
# These are the requests from JDK11's HttpClient non-blocking I/O.
# Notice how we receive all 128 requests at once.
2022-07-24T17:59:41.163Z [129] GET /
(...)
2022-07-24T17:59:41.257Z [256] GET /
2022-07-24T17:59:46.170Z [129] done!
(...)
2022-07-24T17:59:46.276Z [256] done!
# These are there requests from Ktor's HTTP client non-blocking I/O.
# Notice how we also receive all 128 requests at once.
2022-07-24T17:59:46.869Z [257] GET /
(...)
2022-07-24T17:59:46.918Z [384] GET /
2022-07-24T17:59:51.874Z [257] done!
(...)
2022-07-24T17:59:51.921Z [384] done!
关于kotlin - 非阻塞 I/O 和 Kotlin 协程有什么关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73103135/
我正在查看Kotlin Github page我注意到 Kotlin 语言本身大部分是用 Kotlin 编写的:我只是想知道,一种语言怎么可能大部分都是用它自己的语言编写的?在您可以使用正在创建的语言
我有以下非常简单的 kotlin 代码来演示中缀函数 com.lopushen.demo.presentation 包 fun main(args: Array) { print("Hello
我在 Java 中有 2 个模型类,其中一个扩展了另一个 @UseStag public class GenericMessages extends NavigationLocalizationMap
Kotlin 代码 runBlocking { flow { for (i in 0..4) { println("Emit $i")
这三个 Kotlin 插件和它们的实际作用有什么区别? plugins { id 'kotlin-android' id 'org.jetbrains.kotlin.android'
我正在为某些现有库添加 Kotlin 原生 linuxX64 目标支持。库已成功编译,但在运行测试用例时,出现以下运行时错误: kotlin.native.concurrent.InvalidMuta
关闭。这个问题需要details or clarity .它目前不接受答案。 想改进这个问题吗? 通过 editing this post 添加细节并澄清问题. 关闭 2 年前。 Improve t
我创建了一个类并向其添加了一个与成员函数具有相同签名的扩展,并执行了这个方法,它总是执行成员方法。 class Worker { fun work() = "...working" } fun
我知道传递给函数的参数将被视为“val”,即使变量被初始化为“var”。但这对我来说一直是个问题。在下面的示例代码中,我想通过使用函数“changeNum”修改变量“num”的值。但当然,Kotlin
现在,我正在尝试用 Kotlin 重写我的 Java 应用程序。然后,我遇到了日志语句,比如 log.info("do the print thing for {}", arg); 所以我有两种方法可
有点出名article关于许多语言的异步编程模型的状态,指出它们存在“颜色”问题,特别是将生态系统分为两个独立的世界:异步和非异步。以下是这种语言的属性: 每个函数都有一种颜色,红色或蓝色(例如asy
因为 KDoc 文档生成引擎是 abandoned in favor of Dokka , Kotlin 文档应该称为“KDoc 注释”,还是“Dokka 注释”? 最佳答案 如所述here , KD
我想在可空对象上传递函数引用。以 Android 为例,假设我想使用 Activity#onBackPressed来自作为该事件的子级的片段。 如果我想调用这个函数,我可以很容易地做到 activit
我有一个列表 (x, y)其中y只能是 0 或 1 这样 例如: [(3, 0), (3, 1), (5, 1)] [(5, 0), (3, 1), (5, 1)] [(1, 1), (3, 1),
从强类型语言的定义来看: A strongly-typed programming language is one in which each type of data (such as intege
这不能编译的事实是否意味着它们不是一流的类型? fun foo(s: String): Int = s.length // This won't compile. val bar = foo 有没有办
如果在 Java i++是一个表达式和 i++;是一个表达式语句,分号(;) 在 Kotlin 中是可选的,是 i++ Kotlin 中的表达式或表达式语句? 最佳答案 i++是一个表达式,因为它有一
代码(如下所示)是否正确?它取自 Kotlin-docs.pdf 的第 63 页,这也是 https://kotlinlang.org/docs/reference/generics.html 的最后
我正在尝试使用 Kotlin 为 Android 的一些全局 API 解析器(检查网络连接、调用 API 并通过来自源的单个调用返回格式化数据),并且在某些时候我不得不创建一个通用类型 object就
kotlinlang 中的任务: 使用月份变量重写此模式,使其与格式 13 JUN 1992(两位数字、一个空格、一个月份缩写、一个空格、四位数字)中的日期相匹配。 答案是:val month = "
我是一名优秀的程序员,十分优秀!