当前位置:网站首页>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")
}
边栏推荐
- 微信小程序開發工具 POST net::ERR_PROXY_CONNECTION_FAILED 代理問題
- 创建+注册 子应用_定义路由,全局路由与子路由
- 可視化yolov5格式數據集(labelme json文件)
- 【Camera专题】手把手撸一份驱动 到 点亮Camera
- Network security - DNS spoofing and phishing websites
- Asian Games countdown! AI target detection helps host the Asian Games!
- Reprint some Qt development experience written by great Xia 6.5
- Network security - dynamic routing protocol rip
- Caused by: com. fasterxml. jackson. databind. exc.MismatchedInputException: Cannot construct instance o
- Bottleneck period must see: how can testers who have worked for 3-5 years avoid detours and break through smoothly
猜你喜欢
Rockchip3399 start auto load driver
【Camera专题】手把手撸一份驱动 到 点亮Camera
Everything file search tool
In 2022, 95% of the three most common misunderstandings in software testing were recruited. Are you that 5%?
What are the key points often asked in the redis interview
详细些介绍如何通过MQTT协议和华为云物联网进行通信
[leetcode] 797 and 1189 (basis of graph theory)
Some functions of applet development
Performance test | script template sorting, tool sorting and result analysis
Machine learning notes (constantly updating...)
随机推荐
Network security - cracking system passwords
udp接收队列以及多次初始化的测试
2022 spring "golden three silver four" job hopping prerequisites: Software Test interview questions (with answers)
Visual yolov5 format data set (labelme JSON file)
His experience in choosing a startup company or a big Internet company may give you some inspiration
Recommendation letter of "listing situation" -- courage is the most valuable
Performance test | script template sorting, tool sorting and result analysis
[camera topic] turn a drive to light up the camera
How to refresh the opening amount of Oracle ERP
疫情当头,作为Leader如何进行团队的管理?| 社区征文
Network security - DNS spoofing and phishing websites
【Camera专题】HAL层-addChannel和startChannel简析
全链路数字化转型下,零售企业如何打开第二增长曲线
自定义组件、使用npm包、全局数据共享、分包
Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance o
[Appendix 6 Application of reflection] Application of reflection: dynamic agent
Y54. Chapter III kubernetes from introduction to mastery -- ingress (27)
Wechat applet Development Tool Post net:: Err Proxy Connexion Problèmes d'agent défectueux
深度学习笔记(持续更新中。。。)
[Yu Yue education] Jiujiang University material analysis and testing technology reference