当前位置:网站首页>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
边栏推荐
- 维基媒体基金会公布新商业产品“维基媒体企业”首批客户
- VIM from dislike to dependence (21) -- cross file search
- Detectron2 source code reading 2--- using the configurable decorator to build the dataloader
- 挖财开户安全吗?怎么有人说不靠谱。
- Flink Sql -- toAppendStream doesn‘t support consuming update and delete changes which
- Detailed explanation of pytoch's scatter function
- 自制GIF动态图-gifcam
- Sort (simple description)
- 国债逆回购绝对安全吗 网上怎么开户
- Use Huawei performance management service to configure the sampling rate on demand
猜你喜欢
Esp32 things (II): sharpening the knife without mistaking firewood - make preparations before project development
Tidb v6.0.0 (DMR): initial test of cache table - tidb Book rush
C#访问MongoDB并执行CRUD操作
Flink Sql -- toAppendStream doesn‘t support consuming update and delete changes which
Opencv learning notes -day8 (keyboard typing (waitkey()); Wait for typing) action: triggers some action when the appropriate character is typed using the keyboard)
Opencv learning notes-day5 (arithmetic operation of image pixels, add() addition function, subtract() subtraction function, divide() division function, multiply() multiplication function
A troubleshooting of CPU bottom falling
Set, map and modularity
Opencv learning notes -day 12 (ROI region extraction and inrange() function operation)
Evaluation standard for audio signal quality of intelligent speakers
随机推荐
Interpretation of orientedrcnn papers
Unity basic lighting model
Metasploit practice - SSH brute force cracking process
[untitled]
How can I get the discount for opening a securities account? Is online account opening safe?
Implementing custom drawer component in quick application
vim 从嫌弃到依赖(21)——跨文件搜索
Detailed explanation of pytoch's scatter function
C # get the current timestamp
Anchorgenerator for mmdet line by line interpretation
Redis design and Implementation (I) | data structure & object
Esp32 things (V): analysis of common API of esp32 of Swiss Army knife
Introduction to MySQL basics day3 power node [Lao Du] class notes
Flink sql -- No factory implements ‘org. apache. flink. table. delegation. ExecutorFactory‘.
Flink SQL custom connector
Abstract factory pattern
How to format an UTC date to use the Z (Zulu) zone designator in php?
Esp32 (IX): OTA function of function development
C#访问SQL Server数据库两种方式的比较(SqlDataReader vs SqlDataAdapter)
Wechat development tool (applet)