1 /* 2 * Copyright (C) 2017 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 package com.example.android.autofill.service.util; 17 18 import android.os.Handler; 19 import android.os.Looper; 20 import android.support.annotation.NonNull; 21 import android.support.annotation.VisibleForTesting; 22 23 import java.util.concurrent.Executor; 24 import java.util.concurrent.Executors; 25 26 /** 27 * Global executor pools for the whole application. 28 * <p> 29 * Grouping tasks like this avoids the effects of task starvation (e.g. disk reads don't wait behind 30 * webservice requests). 31 */ 32 public class AppExecutors { 33 34 private static final int THREAD_COUNT = 3; 35 36 private final Executor diskIO; 37 38 private final Executor networkIO; 39 40 private final Executor mainThread; 41 42 @VisibleForTesting 43 AppExecutors(Executor diskIO, Executor networkIO, Executor mainThread) { 44 this.diskIO = diskIO; 45 this.networkIO = networkIO; 46 this.mainThread = mainThread; 47 } 48 49 public AppExecutors() { 50 this(new DiskIOThreadExecutor(), Executors.newFixedThreadPool(THREAD_COUNT), 51 new MainThreadExecutor()); 52 } 53 54 public Executor diskIO() { 55 return diskIO; 56 } 57 58 public Executor networkIO() { 59 return networkIO; 60 } 61 62 public Executor mainThread() { 63 return mainThread; 64 } 65 66 private static class MainThreadExecutor implements Executor { 67 private Handler mainThreadHandler = new Handler(Looper.getMainLooper()); 68 69 @Override 70 public void execute(@NonNull Runnable command) { 71 mainThreadHandler.post(command); 72 } 73 } 74 75 /** 76 * Executor that runs a task on a new background thread. 77 */ 78 private static class DiskIOThreadExecutor implements Executor { 79 80 private final Executor mDiskIO; 81 82 public DiskIOThreadExecutor() { 83 mDiskIO = Executors.newSingleThreadExecutor(); 84 } 85 86 @Override 87 public void execute(@NonNull Runnable command) { 88 mDiskIO.execute(command); 89 } 90 } 91 } 92