当前位置:网站首页>Talk about the job experience of kotlin cooperation process
Talk about the job experience of kotlin cooperation process
2022-06-30 09:01:00 【Byte station】

1. Preface
If you want me to take a real thing and Kotlin In the process of cooperation Job Make an analogy , Then I'll take Job Compared to an iceberg in the ocean . Free floating icebergs are about 90% The volume sinks below the surface of the sea , So look at the shape floating on the water and can't guess the shape under the water . Like an iceberg ,Job The functions provided to developers are very simple , But within the framework of the collaborative process Job But did a lot of work . It's crucial , If developers don't go deep into Job Internal implementation mechanism , So in the process of using CO process , He is like a captain who drives a boat and passes an iceberg , Risk of system crash at any time . If you are using a collaborative process in your project , If you want to enjoy the convenience of CO programming and ensure the robustness of the program . So, in-depth understanding Job Internal mechanism , It will make you when you encounter coordination problems , More leisurely , More comfortable .
In order to test your readers' understanding of the collaborative process Job The degree of understanding of , I designed two pieces of code , Which one, please Case “CancelJobActivity job2 finished” The statement will be printed out ?
Procedure 1 :
private fun case1() {
val scope = MainScope()
scope.launch(Job()) {
launch {
delay(2000L)
println("CancelJobActivity job1 finished")
scope.cancel()
}
launch {
delay(3000L)
println("CancelJobActivity job2 finished")
}
}
}
Program two :
private fun case2() {
val scope = MainScope()
scope.launch {
launch {
delay(2000L)
println("CancelJobActivity job1 finished")
scope.cancel()
}
launch {
delay(3000L)
println("CancelJobActivity job2 finished")
}
}
}
The functions of the above two codes are : adopt MainScope Start a process , Start two sub processes in this process . Zixie Cheng 1 stay delay 2s Print the statement and cancel MainScope Start the process , Zixie Cheng 2 stay delay 3s Print the statement after . Our expectation is , Zixie Cheng 1 Calling scope.cancel After the method , Zixie Cheng 2 No statement will be output . Procedure 2 is as we wish , But program one is 3s It still outputs . Obviously, the result of program 1 is not accepted by us . The only difference between them is in scope.launch Are there any Job() Parameters .
Why? launch() Methods add Job() Parameters , You can't cancel the process ? To understand the problem , You have to understand , Data structure in parent-child collaboration . quote Google Official pictures , We can see , This is a typical tree data structure .
2. Cause analysis
- according to MainScope Source code , We know scope Corresponding Job The type is SupervisorJob.
- launch The coroutine created by the method itself is also Job type . And it is related to the CoroutineContext[Job] Form a father son relationship .
- launch(Job()) according to CoroutineContext Of plus Method , Will use the new newJob Instead of SupervisorJob.
public fun MainScope(): CoroutineScope
= ContextScope(SupervisorJob() + Dispatchers.Main)
- CoroutineScope.cancel Method , It is coroutineContext[Job] Corresponding Job cancel Of .
public fun CoroutineScope.cancel(cause: CancellationException? = null) {
val job = coroutineContext[Job] ?: error("Scope cannot be cancelled because it does not have a job: $this")
job.cancel(cause)
}
Diagram of program 2 

Procedure one Job The diagram 

from Job The diagram , We can see that MainScope Corresponding SupervisorJob In program 1 , Separate out , Not with Job0、Job1、Job2 Form an effective tree structure relationship , So pass scope.cancel() Can't cancel .
Last Job I've been thinking about related articles for a long time , because Job More complicated , I can't start for a moment . This article is entitled to be a starting point ,Job Principle and source code combined with the article , It will be updated one after another . The case in this article is just Job The tip of the iceberg ,cancel And exception handling mechanisms , And Job The tree structure diagram can change many situations , But if you can really understand the principle , It's not troublesome to deal with . Next time I'll look at the source code , Explain Job How is the tree structure relationship established , as well as Job Of cancel How the mechanism propagates in both directions and how the exception handling mechanism propagates upward .
If you have any questions, you can join my technical exchange group , Discuss together . The background to reply “ communication ” that will do
边栏推荐
- [kotlin collaboration process] complete the advanced kotlin collaboration process
- Enhance the add / delete operation of for loop & iterator delete collection elements
- Redis design and Implementation (II) | database (deletion strategy & expiration elimination strategy)
- Interpretation of source code demand:a rotation equivariant detector for aerial object detection
- Evaluation standard for audio signal quality of intelligent speakers
- Esp32 things (II): sharpening the knife without mistaking firewood - make preparations before project development
- JVM调优相关命令以及解释
- Implementing custom drawer component in quick application
- 127.0.0.1, 0.0.0.0 and localhost
- Opencv learning notes-day9 opencv's own color table operation (colormap coloraptypes enumeration data types and applycolormap() pseudo color function)
猜你喜欢

Esp32 (4): overview of the overall code architecture

Interpretation of source code demand:a rotation equivariant detector for aerial object detection

TiDB v6.0.0 (DMR) :缓存表初试丨TiDB Book Rush

Deploy the cow like customer network project on the ECS

100 lines of code and a voice conversation assistant

Bind threads to run on a specific CPU logical kernel

Metasploit practice - SSH brute force cracking process

将线程绑定在某个具体的CPU逻辑内核上运行

Does the oscilloscope probe affect the measurement of capacitive load?

Opencv learning notes -day 11 (split() channel separation function and merge() channel merge function)
随机推荐
Esp32 (6): Bluetooth and WiFi functions for function development
Introduction to MySQL basics day3 power node [Lao Du] class notes
Pytorch BERT
Detailed explanation of pytoch's scatter function
JVM tuning related commands and explanations
Six implementation methods of singleton mode
Based on svelte3 X desktop UI component library svelte UI
Detectron2 source code reading 4-- registrar construction model
Deploy the cow like customer network project on the ECS
Influencing factors of echo cancellation for smart speakers
Icon resources
CUDA realizes matrix multiplication
Opencv learning notes -day 11 (split() channel separation function and merge() channel merge function)
Maxiouassigner of mmdet line by line interpretation
[data analysis and display]
Detailed explanation of rect class
维基媒体基金会公布新商业产品“维基媒体企业”首批客户
Alcohol tester scheme: what principle does the alcohol tester measure alcohol solubility based on?
Axure make menu bar effect
Set, map and modularity