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 20 import android.util.Log; 21 22 import java.util.ArrayList; 23 import java.util.List; 24 25 /** 26 * Executes NamedTasks in batches of a given size. Tasks are queued until 27 * executeNextBatch is called. 28 */ 29 public class BatchingNamedTaskExecutor implements NamedTaskExecutor { 30 31 private static final boolean DBG = false; 32 private static final String TAG = "QSB.BatchingNamedTaskExecutor"; 33 34 private final NamedTaskExecutor mExecutor; 35 36 /** Queue of tasks waiting to be dispatched to mExecutor **/ 37 private final ArrayList<NamedTask> mQueuedTasks = new ArrayList<NamedTask>(); 38 39 /** 40 * Creates a new BatchingSourceTaskExecutor. 41 * 42 * @param executor A SourceTaskExecutor for actually executing the tasks. 43 */ BatchingNamedTaskExecutor(NamedTaskExecutor executor)44 public BatchingNamedTaskExecutor(NamedTaskExecutor executor) { 45 mExecutor = executor; 46 } 47 execute(NamedTask task)48 public void execute(NamedTask task) { 49 synchronized (mQueuedTasks) { 50 if (DBG) Log.d(TAG, "Queuing " + task); 51 mQueuedTasks.add(task); 52 } 53 } 54 dispatch(NamedTask task)55 private void dispatch(NamedTask task) { 56 if (DBG) Log.d(TAG, "Dispatching " + task); 57 mExecutor.execute(task); 58 } 59 60 /** 61 * Instructs the executor to submit the next batch of results. 62 * @param batchSize the maximum number of entries to execute. 63 */ executeNextBatch(int batchSize)64 public void executeNextBatch(int batchSize) { 65 NamedTask[] batch = new NamedTask[0]; 66 synchronized (mQueuedTasks) { 67 int count = Math.min(mQueuedTasks.size(), batchSize); 68 List<NamedTask> nextTasks = mQueuedTasks.subList(0, count); 69 batch = nextTasks.toArray(batch); 70 nextTasks.clear(); 71 if (DBG) Log.d(TAG, "Dispatching batch of " + count); 72 } 73 74 for (NamedTask task : batch) { 75 dispatch(task); 76 } 77 } 78 79 /** 80 * Cancel any unstarted tasks running in this executor. This instance 81 * should not be re-used after calling this method. 82 */ cancelPendingTasks()83 public void cancelPendingTasks() { 84 synchronized (mQueuedTasks) { 85 mQueuedTasks.clear(); 86 } 87 } 88 close()89 public void close() { 90 cancelPendingTasks(); 91 mExecutor.close(); 92 } 93 } 94