当前位置:网站首页>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")
}
边栏推荐
- What are the key points often asked in the redis interview
- 力扣(LeetCode)183. 从不订购的客户(2022.07.02)
- 微服务组件Sentinel (Hystrix)详细分析
- Problems encountered in small program development of dark horse shopping mall
- [shutter] hero animation (hero realizes radial animation | hero component createrecttween setting)
- Cfdiv2 fixed point guessing- (interval answer two points)
- File class (check)
- Answers to ten questions about automated testing software testers must see
- 函数的定义和调用、this、严格模式、高阶函数、闭包、递归
- Hard core observation 547 large neural network may be beginning to become aware?
猜你喜欢
Introduce in detail how to communicate with Huawei cloud IOT through mqtt protocol
Visualisation de l'ensemble de données au format yolov5 (fichier labelme json)
[shutter] pull the navigation bar sideways (drawer component | pageview component)
Rockchip3399 start auto load driver
詳細些介紹如何通過MQTT協議和華為雲物聯網進行通信
Anna: Beibei, can you draw?
easyExcel
[shutter] top navigation bar implementation (scaffold | defaulttabcontroller | tabbar | tab | tabbarview)
Asian Games countdown! AI target detection helps host the Asian Games!
Certaines fonctionnalités du développement d'applets
随机推荐
函数的定义和调用、this、严格模式、高阶函数、闭包、递归
Huakaiyun (Zhiyin) | virtual host: what is a virtual host
[leetcode] 797 and 1189 (basis of graph theory)
easyExcel
How can retail enterprises open the second growth curve under the full link digital transformation
es6 filter() 数组过滤方法总结
Analysis, use and extension of open source API gateway apisex
Network security - DNS spoofing and phishing websites
In 2022, 95% of the three most common misunderstandings in software testing were recruited. Are you that 5%?
[shutter] pull the navigation bar sideways (drawer component | pageview component)
小程序开发黑马购物商城中遇到的问题
Network security OpenVAS
[fluent] hero animation (hero animation use process | create hero animation core components | create source page | create destination page | page Jump)
Learn BeanShell before you dare to say you know JMeter
《上市风云》荐书——唯勇气最可贵
PS remove watermark details
Rockchip3399 start auto load driver
How to find summer technical internship in junior year? Are you looking for a large company or a small company for technical internship?
[camera topic] turn a drive to light up the camera
Network security ACL access control list