Home | History | Annotate | Download | only in util
      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 java.util.HashMap;
     21 
     22 /**
     23  * Uses a separate executor for each task name.
     24  */
     25 public 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         if (mExecutors == null) return;
     39         for (NamedTaskExecutor executor : mExecutors.values()) {
     40             executor.cancelPendingTasks();
     41         }
     42     }
     43 
     44     public synchronized void close() {
     45         if (mExecutors == null) return;
     46         for (NamedTaskExecutor executor : mExecutors.values()) {
     47             executor.close();
     48         }
     49     }
     50 
     51     public synchronized void execute(NamedTask task) {
     52         if (mExecutors == null) {
     53             mExecutors = new HashMap<String, NamedTaskExecutor>();
     54         }
     55         String name = task.getName();
     56         NamedTaskExecutor executor = mExecutors.get(name);
     57         if (executor == null) {
     58             executor = mExecutorFactory.create();
     59             mExecutors.put(name, executor);
     60         }
     61         executor.execute(task);
     62     }
     63 
     64 }
     65