1 package org.apache.lucene.util;
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 import java.util.concurrent.Executors;
21 import java.util.concurrent.ThreadFactory;
22 import java.util.concurrent.atomic.AtomicInteger;
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()}.
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;
38 * Creates a new {@link NamedThreadFactory} instance
40 * @param threadNamePrefix the name prefix assigned to each thread created.
42 public NamedThreadFactory(String threadNamePrefix) {
43 final SecurityManager s = System.getSecurityManager();
44 group = (s != null) ? s.getThreadGroup() : Thread.currentThread()
46 this.threadNamePrefix = String.format(NAME_PATTERN,
47 checkPrefix(threadNamePrefix), threadPoolNumber.getAndIncrement());
50 private static String checkPrefix(String prefix) {
51 return prefix == null || prefix.length() == 0 ? "Lucene" : prefix;
55 * Creates a new {@link Thread}
57 * @see java.util.concurrent.ThreadFactory#newThread(java.lang.Runnable)
59 public Thread newThread(Runnable r) {
60 final Thread t = new Thread(group, r, String.format("%s-%d",
61 this.threadNamePrefix, threadNumber.getAndIncrement()), 0);
63 t.setPriority(Thread.NORM_PRIORITY);