PerNameExecutor.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 19 20import java.util.HashMap; 21 22/** 23 * Uses a separate executor for each task name. 24 */ 25public class PerNameExecutor implements NamedTaskExecutor { 26 27 private final Factory<NamedTaskExecutor> mExecutorFactory; 28 private HashMap<String, NamedTaskExecutor> mExecutors; 29 30 /** 31 * @param executorFactory Used to run the commands. 32 */ 33 public PerNameExecutor(Factory<NamedTaskExecutor> executorFactory) { 34 mExecutorFactory = executorFactory; 35 } 36 37 public synchronized void cancelPendingTasks() { 38 for (NamedTaskExecutor executor : mExecutors.values()) { 39 executor.cancelPendingTasks(); 40 } 41 } 42 43 public synchronized void close() { 44 for (NamedTaskExecutor executor : mExecutors.values()) { 45 executor.close(); 46 } 47 } 48 49 public synchronized void execute(NamedTask task) { 50 if (mExecutors == null) { 51 mExecutors = new HashMap<String, NamedTaskExecutor>(); 52 } 53 String name = task.getName(); 54 NamedTaskExecutor executor = mExecutors.get(name); 55 if (executor == null) { 56 executor = mExecutorFactory.create(); 57 mExecutors.put(name, executor); 58 } 59 executor.execute(task); 60 } 61 62} 63