当前位置:网站首页>Cancellation of collaboration in kotlin, side effects of cancellation and overtime tasks
Cancellation of collaboration in kotlin, side effects of cancellation and overtime tasks
2022-07-03 02:07:00 【yu-Knight】
Kotlin Cancellation of the middle process, the side effects of cancellation and overtime tasks
Cancellation of the agreement
- The scope of the subprocess will be canceled .
- The rest of the process will not be affected .
- A coroutine throws a special exception CancellationException To handle the cancellation .
- all kotlinx.coroutines Suspend function in (withContext、delay etc. ) Can be cancelled .
@Test
fun `test scope cancel`() = runBlocking<Unit> {
val scope = CoroutineScope(Dispatchers.Default)
scope.launch {
delay(1000)
println("job 1")
}
scope.launch {
delay(1000)
println("job 2")
}
delay(1000)
scope.cancel() // Cancel scope
//runBlocking The process waits for the sub process to run
delay(2000)
}
@Test
fun `test brother cancel`() = runBlocking<Unit> {
val scope = CoroutineScope(Dispatchers.Default)
val job1 = scope.launch {
delay(1000)
println("job 1")
}
val job2 = scope.launch {
delay(1000)
println("job 2")
}
delay(100)
job1.cancel() // Cancel scope ,job2 No effect
//runBlocking The process waits for the sub process to run
delay(2000)
}
@Test
fun `test CancellationException`() = runBlocking<Unit> {
val job1 = GlobalScope.launch {
try {
delay(1000)
println("job 1")
} catch (e: Exception) {
e.printStackTrace()
}
}
delay(100)
// job1.cancel(CancellationException(" Cancel the program "))
// job1.join()
job1.cancelAndJoin()
}
CPU Intensive tasks are cancelled
- 1.isActive Is one that can be used in CoroutioneScope Extended properties in , Check Job Is it active or not .
- 2.ensureActive(), If job It's inactive , This method will immediately throw an exception .
- 3.yield The function checks the state of the coroutine , If it has been cancelled , Throw out CancellationException Respond . In addition, it will try to transfer the execution right of the thread , Provide implementation opportunities for other collaborative processes .
@Test
fun `test cancel cpu task by isActive`() = runBlocking<Unit> {
val startTime = System.currentTimeMillis()
val job = launch(Dispatchers.Default) {
var nextPrintTime = startTime
var i = 0
while (i < 5 && isActive) {
//isActive Judge cancel Is it called , Not called true
if (System.currentTimeMillis() >= nextPrintTime) {
println("job: I'm sleeping")
nextPrintTime += 500
}
}
}
delay(1300)
println("main: I'm tired of waiting")
job.cancelAndJoin()
println("main: Now I can quit")
}
@Test
fun `test cancel cpu task by ensureActive`() = runBlocking<Unit> {
val startTime = System.currentTimeMillis()
val job = launch(Dispatchers.Default) {
var nextPrintTime = startTime
var i = 0
while (i < 5) {
ensureActive() // Exiting the subprocess will throw an exception , Exceptions are handled silently , You can capture it manually
if (System.currentTimeMillis() >= nextPrintTime) {
println("job: I'm sleeping")
nextPrintTime += 500
}
}
}
delay(1300)
println("main: I'm tired of waiting")
job.cancelAndJoin()
println("main: Now I can quit")
}
@Test
fun `test cancel cpu task by yield`() = runBlocking<Unit> {
val startTime = System.currentTimeMillis()
val job = launch(Dispatchers.Default) {
var nextPrintTime = startTime
var i = 0
while (i < 5) {
yield() // Exiting the subprocess will throw an exception , Exceptions are handled silently , You can capture it manually
if (System.currentTimeMillis() >= nextPrintTime) {
println("job: I'm sleeping")
nextPrintTime += 500
}
}
}
delay(1300)
println("main: I'm tired of waiting")
job.cancelAndJoin()
println("main: Now I can quit")
}
Side effects of synergetic cancellation
- 1. stay finally Release resources in .
- 2.use function : This function can only be implemented Closeable Object using , When the program ends, it will automatically call close Method , Suitable for file objects .
@Test
fun `test crelease resources`() = runBlocking<Unit> {
var job = launch {
try {
repeat(1000) {
i ->
println("job: I'm sleeping $i")
delay(500L)
}
} finally {
// Release resources
println("job: I'm running finally")
}
}
delay(1300)
println("main: I'm tired of waiting")
job.cancelAndJoin()
println("main: Now I can quit")
}
@Test
fun `test use function`() = runBlocking<Unit> {
var br = BufferedReader(FileReader("D:\\a.txt"))
with(br) {
var line: String?
try {
while (true) {
line = readLine() ?: break;
println(line)
}
} finally {
close()
}
}
//use Function auto call close Method Close release resources
BufferedReader(FileReader("D:\\a.txt")).use {
var line: String?
while (true) {
line = it.readLine() ?: break;
println(line)
}
}
}
Tasks that cannot be cancelled
- 1. A collaboration in the canceling state cannot be suspended ( Run code that cannot be cancelled ), When the coroutine is cancelled, you need to call the suspend function , We need to put the code for the cleanup task in NonCancellable CoroutineContext in .
- 2. This will suspend running code , And keep the cancellation status of the cooperation process until the task processing is completed .
@Test
fun `test cancel with NonCancellable`() = runBlocking<Unit> {
var job = launch {
try {
repeat(1000) {
i ->
println("job: I'm sleeping $i")
delay(500L)
}
} finally {
// Release resources
// Use when canceling the collaboration withContext Come without affecting finally Execution content in
withContext(NonCancellable){
println("job: I'm running finally")
delay(1000L)
println("job: And I've just delayed for 1 sec because I'm non-cancellable")
}
}
}
delay(1300)
println("main: I'm tired of waiting")
job.cancelAndJoin()
println("main: Now I can quit")
}
Overtime task
- 1. In many cases, the reason to cancel a collaboration is that it may time out .
- 2.withTimeoutOrNull By returning null To time out , Instead of throwing an exception .
@Test
fun `test deal with timeout`() = runBlocking<Unit> {
withTimeout(1300){
repeat(1000){
i->
println("job: I'm sleeping $i")
delay(500L)
}
}
}
@Test
fun `test deal with timeout return null`() = runBlocking<Unit> {
val result = withTimeoutOrNull(1300){
repeat(1000){
i->
println("job: I'm sleeping $i")
delay(500L)
}
"Done"
} ?:"yuknight"
println("Result is $result")
}
边栏推荐
- Redis:Redis的简单使用
- 【Camera专题】HAL层-addChannel和startChannel简析
- 创建+注册 子应用_定义路由,全局路由与子路由
- 技术大佬准备就绪,话题C位由你决定
- Huakaiyun | virtual host: IP, subnet mask, gateway, default gateway
- PS remove watermark details
- Technology sharing | Frida's powerful ability to realize hook functions
- Where is the future of test engineers? Confused to see
- [shutter] pull the navigation bar sideways (drawer component | pageview component)
- [camera topic] complete analysis of camera dtsi
猜你喜欢

Depth (penetration) selector:: v-deep/deep/ and > > >

easyExcel

Bottleneck period must see: how can testers who have worked for 3-5 years avoid detours and break through smoothly

小程序開發的部分功能

自定义组件、使用npm包、全局数据共享、分包

udp接收队列以及多次初始化的测试

What are the key points often asked in the redis interview

What are the differences between software testers with a monthly salary of 7K and 25K? Leaders look up to you when they master it
![[shutter] shutter debugging (debugging fallback function | debug method of viewing variables in debugging | console information)](/img/66/0fda43da0d36fc0c9277ca86ece252.jpg)
[shutter] shutter debugging (debugging fallback function | debug method of viewing variables in debugging | console information)

深度学习笔记(持续更新中。。。)
随机推荐
[Yu Yue education] reference materials of chemical experiment safety knowledge of University of science and technology of China
Asian Games countdown! AI target detection helps host the Asian Games!
Everything file search tool
Iptables layer 4 forwarding
Where is the future of test engineers? Confused to see
Machine learning notes (constantly updating...)
Huakaiyun | virtual host: IP, subnet mask, gateway, default gateway
The Sandbox阐释对元宇宙平台的愿景
查询商品案例-页面渲染数据
小程序开发黑马购物商城中遇到的问题
机器学习流程与方法
去除网页滚动条方法以及内外边距
[shutter] top navigation bar implementation (scaffold | defaulttabcontroller | tabbar | tab | tabbarview)
leetcode961. Find the elements repeated N times in the array with length 2n
Problems encountered in small program development of dark horse shopping mall
小程序開發的部分功能
微信小程序开发工具 POST net::ERR_PROXY_CONNECTION_FAILED 代理问题
【Camera专题】OTP数据如何保存在自定义节点中
How do browsers render pages?
His experience in choosing a startup company or a big Internet company may give you some inspiration