add --shared
[pylucene.git] / lucene-java-3.4.0 / lucene / src / java / org / apache / lucene / util / NamedThreadFactory.java
1 package org.apache.lucene.util;
2
3 /**
4  * Licensed to the Apache Software Foundation (ASF) under one or more
5  * contributor license agreements.  See the NOTICE file distributed with
6  * this work for additional information regarding copyright ownership.
7  * The ASF licenses this file to You under the Apache License, Version 2.0
8  * (the "License"); you may not use this file except in compliance with
9  * the License.  You may obtain a copy of the License at
10  *
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19
20 import java.util.concurrent.Executors;
21 import java.util.concurrent.ThreadFactory;
22 import java.util.concurrent.atomic.AtomicInteger;
23
24 /**
25  * A default {@link ThreadFactory} implementation that accepts the name prefix
26  * of the created threads as a constructor argument. Otherwise, this factory
27  * yields the same semantics as the thread factory returned by
28  * {@link Executors#defaultThreadFactory()}.
29  */
30 public class NamedThreadFactory implements ThreadFactory {
31   private static final AtomicInteger threadPoolNumber = new AtomicInteger(1);
32   private final ThreadGroup group;
33   private final AtomicInteger threadNumber = new AtomicInteger(1);
34   private static final String NAME_PATTERN = "%s-%d-thread";
35   private final String threadNamePrefix;
36
37   /**
38    * Creates a new {@link NamedThreadFactory} instance
39    * 
40    * @param threadNamePrefix the name prefix assigned to each thread created.
41    */
42   public NamedThreadFactory(String threadNamePrefix) {
43     final SecurityManager s = System.getSecurityManager();
44     group = (s != null) ? s.getThreadGroup() : Thread.currentThread()
45         .getThreadGroup();
46     this.threadNamePrefix = String.format(NAME_PATTERN,
47         checkPrefix(threadNamePrefix), threadPoolNumber.getAndIncrement());
48   }
49
50   private static String checkPrefix(String prefix) {
51     return prefix == null || prefix.length() == 0 ? "Lucene" : prefix;
52   }
53
54   /**
55    * Creates a new {@link Thread}
56    * 
57    * @see java.util.concurrent.ThreadFactory#newThread(java.lang.Runnable)
58    */
59   public Thread newThread(Runnable r) {
60     final Thread t = new Thread(group, r, String.format("%s-%d",
61         this.threadNamePrefix, threadNumber.getAndIncrement()), 0);
62     t.setDaemon(false);
63     t.setPriority(Thread.NORM_PRIORITY);
64     return t;
65   }
66
67 }