1 /*
2  * Copyright 2022 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 androidx.work.testing
18 
19 import androidx.annotation.GuardedBy
20 import androidx.work.impl.utils.taskexecutor.SerialExecutor
21 
22 internal class SynchronousSerialExecutor : SerialExecutor {
23     private val lock = Any()
24 
25     @GuardedBy("lock") private val tasks = ArrayDeque<Runnable>()
26 
27     @GuardedBy("lock") private var isRunning = false
28 
executenull29     override fun execute(command: Runnable) {
30         synchronized(lock) {
31             tasks.add(command)
32             if (isRunning) return
33             isRunning = true
34         }
35         do {
36             // running potentially long task without the lock
37             // so other threads can grab the lock to add runnables to the queue
38             synchronized(lock) { tasks.removeFirstOrNull() }?.run()
39             // check if new tasks were added while the previous was ran.
40             synchronized(lock) { isRunning = tasks.isNotEmpty() }
41         } while (isRunning)
42     }
43 
hasPendingTasksnull44     override fun hasPendingTasks(): Boolean {
45         return synchronized(lock) { tasks.isNotEmpty() }
46     }
47 }
48