/*
* Copyright 2007-2010 Sun Microsystems, Inc.
*
* This file is part of Project Darkstar Server.
*
* Project Darkstar Server is free software: you can redistribute it
* and/or modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation and
* distributed hereunder to you.
*
* Project Darkstar Server is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*/
package com.sun.sgs.impl.util;
import com.sun.sgs.impl.sharedutil.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.ThreadFactory;
/**
* A custom implementation of a {@code ThreadFactory} that assigns a
* configurable name to each thread.
*/
public class NamedThreadFactory implements ThreadFactory {
// the prefix to assign to the name of each thread generated by the factory
private final String name;
// a running count of the number of threads generated by this factory
private final AtomicInteger count;
/**
* Creates a new {@code NamedThreadFactory} that names each thread that
* it creates using the given {@code name}.
*
* @param name the prefix to use for each thread's name
*/
public NamedThreadFactory(String name) {
Objects.checkNull("name", name);
this.name = name;
this.count = new AtomicInteger();
}
/**
* Constructs a new {@code Thread} for the given {@code Runnable}. The
* name of the returned {@code Thread} is equal to the current count of the
* number of threads that have been created thus far with this factory
* appended to the name used to construct this factory.
*
* @param r the {@code Runnable} to be executed by the new thread
* @return new thread associated with the given {@code Runnable}
*/
@Override
public Thread newThread(Runnable r) {
return new Thread(r, name + "-" + count.getAndIncrement());
}
}