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