1 /*
2  * Copyright (C) 2009 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 vogar.util;
18 
19 import java.util.concurrent.ExecutorService;
20 import java.util.concurrent.LinkedBlockingQueue;
21 import java.util.concurrent.ThreadFactory;
22 import java.util.concurrent.ThreadPoolExecutor;
23 import java.util.concurrent.TimeUnit;
24 
25 /**
26  * Utility methods for working with threads.
27  */
28 public final class Threads {
Threads()29     private Threads() {}
30 
daemonThreadFactory(final String name)31     public static ThreadFactory daemonThreadFactory(final String name) {
32         return new ThreadFactory() {
33             private int nextId = 0;
34             public synchronized Thread newThread(Runnable r) {
35                 Thread thread = new Thread(r, name + "-" + (nextId++));
36                 thread.setDaemon(true);
37                 return thread;
38             }
39         };
40     }
41 
threadPerCpuExecutor(String name)42     public static ExecutorService threadPerCpuExecutor(String name) {
43         return fixedThreadsExecutor(name, Runtime.getRuntime().availableProcessors());
44     }
45 
fixedThreadsExecutor(String name, int count)46     public static ExecutorService fixedThreadsExecutor(String name, int count) {
47         ThreadFactory threadFactory = daemonThreadFactory(name);
48 
49         return new ThreadPoolExecutor(count, count, 10, TimeUnit.SECONDS,
50                 new LinkedBlockingQueue<Runnable>(Integer.MAX_VALUE), threadFactory) {
51             @Override protected void afterExecute(Runnable runnable, Throwable throwable) {                if (throwable != null) {
52                     Log.info("Unexpected failure from " + runnable, throwable);
53                 }
54             }
55         };
56     }
57 }
58