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      */
registerTasknull38     fun registerTask(name: String): Runnable {
39         pendingTasksCount.incrementAndGet()
40         Trace.beginAsyncSection("PendingTasksContainer#$name", 0)
41 
42         return Runnable {
43             Trace.endAsyncSection("PendingTasksContainer#$name", 0)
44             if (pendingTasksCount.decrementAndGet() == 0) {
45                 val onComplete = completionCallback.getAndSet(null)
46                 onComplete?.run()
47             }
48         }
49     }
50 
51     /**
52      * Clears state and initializes the container
53      */
resetnull54     fun reset() {
55         // Create new objects in case if there are pending callbacks from the previous invocations
56         completionCallback = AtomicReference()
57         pendingTasksCount = AtomicInteger(0)
58     }
59 
60     /**
61      * Starts waiting for all tasks to be completed
62      * When all registered tasks complete it will invoke the [onComplete] callback
63      */
onTasksCompletenull64     fun onTasksComplete(onComplete: Runnable) {
65         completionCallback.set(onComplete)
66 
67         if (pendingTasksCount.get() == 0) {
68             val currentOnComplete = completionCallback.getAndSet(null)
69             currentOnComplete?.run()
70         }
71     }
72 
73     /**
74      * Returns current pending tasks count
75      */
getPendingCountnull76     fun getPendingCount(): Int = pendingTasksCount.get()
77 }
78 
79