Task Governance at Startup - Leveraging Topological Sort

background

In our app development, we will always encounter various tasks that need to be initialized, and each task will have various dependencies before and after, so what should we do! Manually adding dependencies will definitely lead to excessive later dependency costs, so we will definitely introduce various frameworks to solve this problem. So let's implement such a framework today!

Target

What we want to accomplish is:

  1. Support Task automatic dependency conversion, that is, we want to realize that no matter how our tasks are defined, as long as the dependencies of tasks are declared, the processing relationship between tasks can be automatically processed
  2. Support task cycle dependency detection, that is, if there is a cycle dependency in our task, then we must give relevant prompts

topology algorithm

Here we begin to introduce a small algorithm, which is the topological sorting algorithm (to topologically sort a Directed Acyclic Graph (DAG for short) G, which is to arrange all the vertices in G into a linear sequence, so that any one in the graph For vertices u and v, if the edge <u,v>∈E(G), then u appears before v in the linear sequence. Usually, such a linear sequence is called a sequence that satisfies the topological order (Topological Order), referred to as topology Sequence. Simply put, a total order on a set is obtained from a partial order on a certain set . This operation is called topological sorting.) Well, we read the official explanation that we don’t know what it means. Let’s directly Look at the picture below!

insert image description here

You can see the picture above. Simply put, the topology algorithm is to "flatten" a picture, and in this "flattened" picture, all the arrows are in the same direction.

There are many ways to implement topological sorting, such as BFS (breadth-first traversal), DFS (depth-first traversal), here we use BFS to achieve

The steps of the BFS-based topological sorting algorithm are as follows:

  1. Calculate the in-degree of each node in the graph: traverse all edges, and count the in-degree of each node (that is, the number of edges pointing to the node).
  2. Create a queue and add all nodes whose in-degree is 0 to the queue. These nodes have no predecessors and can be processed immediately.
  3. Enter the loop: when the queue is not empty, perform the following operations:

a. Take a node from the queue and add it to the result list of topological sorting.

b. Traverse all edges starting with this node, and decrease the in-degree of the end point of the edge by 1. If the terminal in-degree of an edge becomes 0, it is enqueued, indicating that this node can be processed.

c. Delete the node and its edges.

  1. If the number of nodes in the result list is the same as the number of nodes in the graph, it means that all nodes have been processed and the topological sort is successful. If not, it means that there is a cycle in the graph, and the topological sorting fails.

Through the above algorithm, we can achieve the content of goal 1. Next, we still have goal 2. How to detect the ring and give the specific node? We can use the condition of reducing the in-degree in step b, and we can know that when a ring occurs, there must be a node whose in-degree is not 0, and this node is the ring node we need!

Look directly at the code

val indegree = hashMapOf<ITask, Int>()
val queue = LinkedList<ITask>()
val cycleNodes = mutableListOf<ITask>()
计算所有节点的入度
taskGraph.keys.forEach {
    
     it ->
    taskGraph[it]?.forEach {
    
     itask ->

        indegree[itask] = indegree.getOrElse(itask) {
    
     0 } + 1
    }
}
taskGraph 是一个图的邻接表实现
taskGraph.keys.forEach {
    
    
    if (indegree.getOrElse(it) {
    
     0 } == 0) {
    
    
        queue.offer(it)
    }
}
var count = 0
val result = mutableListOf<ITask>()

进入BFS
while (queue.isNotEmpty()) {
    
    
    val node = queue.poll() ?: break
    result.add(node)
    count++
    taskGraph[node]?.forEach {
    
    
        indegree[it] = indegree.getOrElse(it) {
    
     1 } - 1
        if (indegree[it] == 0) {
    
    
            queue.offer(it)
        }
    }
}
环检测
if (count != allTaskSet.size) {
    
    
    for (entry in indegree) {
    
    
        if (entry.value > 0) {
    
    
            cycleNodes.add(entry.key)
        }
    }
    throw java.lang.RuntimeException("find cycle dependents $cycleNodes")

}
return result

(ps: This model is not very easy to use. It needs to be trained to write the correct code. The above code has been partially corrected by me)

In fact, ITask is an interface we defined

interface ITask {
    
    
    fun handleTask(context:Context)
}

Through the above method, we can get a list sorted by topological algorithm. At this time, we only need to traverse it once and call the method of each ITask.

 val list = detectCycleNodes()
    list.forEach {
    
    
        it.handleTask(context)
    }

Summarize

By understanding a small algorithm, we can solve the problem of task chaos governance at startup

at last

If you want to become an architect or want to break through the 20-30K salary range, then don't be limited to coding and business, but you must be able to select models, expand, and improve programming thinking. In addition, a good career plan is also very important, and the habit of learning is very important, but the most important thing is to be able to persevere. Any plan that cannot be implemented consistently is empty talk.

If you have no direction, here I would like to share with you a set of "Advanced Notes on the Eight Major Modules of Android" written by the senior architect of Ali, to help you organize the messy, scattered and fragmented knowledge systematically, so that you can systematically and efficiently Master the various knowledge points of Android development.
insert image description here
Compared with the fragmented content we usually read, the knowledge points of this note are more systematic, easier to understand and remember, and are arranged strictly according to the knowledge system.

Full set of video materials:

1. Interview collection

insert image description here
2. Source code analysis collection
insert image description here

3. The collection of open source frameworks
insert image description here
welcomes everyone to support with one click and three links. If you need the information in the article, directly scan the CSDN official certification WeChat card at the end of the article to get it for free↓↓↓

PS: There is also a ChatGPT robot in the group, which can answer your work or technical questions

Guess you like

Origin blog.csdn.net/weixin_43440181/article/details/131049259