MicroSpaceThreadFactory.java

package org.microspace.thread;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 
 * @author Gaspar Sinai - {@literal gaspar.sinai@microspace.org}
 * @version 2017-11-04
 */
public class MicroSpaceThreadFactory implements ThreadFactory {
	final String group;
	final AtomicInteger current;
	final ConcurrentHashMap<String, Thread> threads = new ConcurrentHashMap<>();
	
	public MicroSpaceThreadFactory (String group) {
		this.group = group;
		this.current = new AtomicInteger();
	}
	
	public void shutdown() throws InterruptedException {
		for (Thread t : threads.values()) {
			t.interrupt();
			t.join(10000L);
		}
		threads.clear();
	}
	
	@Override
	public Thread newThread(Runnable r) {
		String threadName = group + "-" + current.incrementAndGet();
		Thread ret = new Thread(r, threadName);
		threads.put(threadName, ret);
		return ret;
	}
	
	public int size () {
		return current.get();
	}
}