1 /*
2  * Copyright (C) 2010 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.quicksearchbox.util;
18 
19 import java.util.LinkedList;
20 import java.util.concurrent.Executor;
21 
22 /**
23  * A simple executor that maintains a queue and executes one task synchronously every
24  * time {@link #runNext()} is called. This gives us predictable scheduling for the tests to
25  * avoid timeouts waiting for threads to finish.
26  */
27 public class MockExecutor implements Executor {
28 
29     private final LinkedList<Runnable> mQueue = new LinkedList<Runnable>();
30 
31     private boolean mClosed = false;
32 
execute(Runnable task)33     public void execute(Runnable task) {
34         if (mClosed) throw new IllegalStateException("closed");
35         mQueue.addLast(task);
36     }
37 
cancelPendingTasks()38     public void cancelPendingTasks() {
39         mQueue.clear();
40     }
41 
close()42     public void close() {
43         cancelPendingTasks();
44         mClosed = true;
45     }
46 
countPendingTasks()47     public int countPendingTasks() {
48         return mQueue.size();
49     }
50 
runNext()51     public boolean runNext() {
52         if (mQueue.isEmpty()) {
53             return false;
54         }
55         Runnable command = mQueue.removeFirst();
56         command.run();
57         return true;
58     }
59 
60 }
61