1 /*
2  * Copyright (C) 2021 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.systemui.util.concurrency
18 
19 import android.os.Trace
20 import java.util.concurrent.atomic.AtomicInteger
21 import java.util.concurrent.atomic.AtomicReference
22 
23 /**
24  * Allows to wait for multiple callbacks and notify when the last one is executed
25  */
26 class PendingTasksContainer {
27 
28     @Volatile
29     private var pendingTasksCount = AtomicInteger(0)
30 
31     @Volatile
32     private var completionCallback = AtomicReference<Runnable>()
33 
34     /**
35      * Registers a task that we should wait for
36      * @return a runnable that should be invoked when the task is finished
37      */
38     fun registerTask(name: String): Runnable {
39         pendingTasksCount.incrementAndGet()
40 
41         if (ENABLE_TRACE) {
42             Trace.beginAsyncSection("PendingTasksContainer#$name", 0)
43         }
44 
45         return Runnable {
46             if (pendingTasksCount.decrementAndGet() == 0) {
47                 val onComplete = completionCallback.getAndSet(null)
48                 onComplete?.run()
49 
50                 if (ENABLE_TRACE) {
51                     Trace.endAsyncSection("PendingTasksContainer#$name", 0)
52                 }
53             }
54         }
55     }
56 
57     /**
58      * Clears state and initializes the container
59      */
60     fun reset() {
61         // Create new objects in case if there are pending callbacks from the previous invocations
62         completionCallback = AtomicReference()
63         pendingTasksCount = AtomicInteger(0)
64     }
65 
66     /**
67      * Starts waiting for all tasks to be completed
68      * When all registered tasks complete it will invoke the [onComplete] callback
69      */
70     fun onTasksComplete(onComplete: Runnable) {
71         completionCallback.set(onComplete)
72 
73         if (pendingTasksCount.get() == 0) {
74             val currentOnComplete = completionCallback.getAndSet(null)
75             currentOnComplete?.run()
76         }
77     }
78 
79     /**
80      * Returns current pending tasks count
81      */
82     fun getPendingCount(): Int = pendingTasksCount.get()
83 }
84 
85 private const val ENABLE_TRACE = false
86