当前位置:网站首页>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")
}
边栏推荐
猜你喜欢
stm32F407-------ADC
[shutter] hero animation (hero realizes radial animation | hero component createrecttween setting)
Everything file search tool
elastic stack
Performance test | script template sorting, tool sorting and result analysis
In the face of difficult SQL requirements, HQL is not afraid
stm32F407-------ADC
[camera topic] turn a drive to light up the camera
全链路数字化转型下,零售企业如何打开第二增长曲线
微信小程序開發工具 POST net::ERR_PROXY_CONNECTION_FAILED 代理問題
随机推荐
[shutter] hero animation (hero realizes radial animation | hero component createrecttween setting)
Comment communiquer avec Huawei Cloud IOT via le Protocole mqtt
The technology boss is ready, and the topic of position C is up to you
[shutter] pull the navigation bar sideways (drawer component | pageview component)
Network security - Information Collection
stm32F407-------ADC
各国Web3现状与未来
DDL basic operation
Network security - man in the middle attack
[Yu Yue education] China Ocean University job search OMG reference
詳細些介紹如何通過MQTT協議和華為雲物聯網進行通信
502 (bad gateway) causes and Solutions
[shutter] top navigation bar implementation (scaffold | defaulttabcontroller | tabbar | tab | tabbarview)
可視化yolov5格式數據集(labelme json文件)
Solution for processing overtime orders (Overtime unpaid)
Return the only different value (de duplication)
How to find summer technical internship in junior year? Are you looking for a large company or a small company for technical internship?
Hard core observation 547 large neural network may be beginning to become aware?
疫情當頭,作為Leader如何進行團隊的管理?| 社區征文
Trial setup and use of idea GoLand development tool