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