1 /* 2 * Copyright 2019 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 androidx.camera.core.impl.utils.executor; 18 19 import androidx.camera.core.CameraXThreads; 20 21 import org.jspecify.annotations.NonNull; 22 23 import java.util.Locale; 24 import java.util.concurrent.Executor; 25 import java.util.concurrent.ExecutorService; 26 import java.util.concurrent.Executors; 27 import java.util.concurrent.ThreadFactory; 28 import java.util.concurrent.atomic.AtomicInteger; 29 30 /** 31 * A singleton executor which should be used for I/O tasks. 32 */ 33 // TODO(b/115779693): Make this executor configurable 34 final class IoExecutor implements Executor { 35 private static volatile Executor sExecutor; 36 37 private final ExecutorService mIoService = 38 Executors.newFixedThreadPool( 39 2, 40 new ThreadFactory() { 41 private static final String THREAD_NAME_STEM = 42 CameraXThreads.TAG + "camerax_io_%d"; 43 44 private final AtomicInteger mThreadId = new AtomicInteger(0); 45 46 @Override 47 public Thread newThread(Runnable r) { 48 Thread t = new Thread(r); 49 t.setName( 50 String.format( 51 Locale.US, 52 THREAD_NAME_STEM, 53 mThreadId.getAndIncrement())); 54 return t; 55 } 56 }); 57 getInstance()58 static Executor getInstance() { 59 if (sExecutor != null) { 60 return sExecutor; 61 } 62 synchronized (IoExecutor.class) { 63 if (sExecutor == null) { 64 sExecutor = new IoExecutor(); 65 } 66 } 67 68 return sExecutor; 69 } 70 71 @Override execute(@onNull Runnable command)72 public void execute(@NonNull Runnable command) { 73 mIoService.execute(command); 74 } 75 } 76