001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *   http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.eclipse.aether.util.concurrency;
020
021import java.util.concurrent.Executors;
022import java.util.concurrent.ThreadFactory;
023import java.util.concurrent.atomic.AtomicInteger;
024
025/**
026 * A factory to create worker threads with a given name prefix.
027 */
028public final class WorkerThreadFactory implements ThreadFactory {
029
030    private final ThreadFactory factory;
031
032    private final String namePrefix;
033
034    private final AtomicInteger threadIndex;
035
036    private static final AtomicInteger POOL_INDEX = new AtomicInteger();
037
038    /**
039     * Creates a new thread factory whose threads will have names using the specified prefix.
040     *
041     * @param namePrefix The prefix for the thread names, may be {@code null} or empty to derive the prefix from the
042     *            caller's simple class name.
043     */
044    public WorkerThreadFactory(String namePrefix) {
045        this.factory = Executors.defaultThreadFactory();
046        this.namePrefix =
047                ((namePrefix != null && !namePrefix.isEmpty()) ? namePrefix : getCallerSimpleClassName() + '-')
048                        + POOL_INDEX.getAndIncrement()
049                        + '-';
050        threadIndex = new AtomicInteger();
051    }
052
053    private static String getCallerSimpleClassName() {
054        StackTraceElement[] stack = new Exception().getStackTrace();
055        if (stack == null || stack.length <= 2) {
056            return "Worker-";
057        }
058        String name = stack[2].getClassName();
059        name = name.substring(name.lastIndexOf('.') + 1);
060        return name;
061    }
062
063    public Thread newThread(Runnable r) {
064        Thread thread = factory.newThread(r);
065        thread.setName(namePrefix + threadIndex.getAndIncrement());
066        thread.setDaemon(true);
067        return thread;
068    }
069}