Skip to content

Instantly share code, notes, and snippets.

@manzke
Created August 24, 2013 22:04
Show Gist options
  • Select an option

  • Save manzke/6330675 to your computer and use it in GitHub Desktop.

Select an option

Save manzke/6330675 to your computer and use it in GitHub Desktop.
Threads.java - Should be used if you are working with Executors and don't want that they are going to stop your shutdown
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Utility class for thread treatment.
*/
public final class Threads {
private Threads() {
}
/**
* Creates a new {@link ThreadFactory} which only creates daemon {@link Threads}. So the JVM
* will shutdown nether the less if there are submitted jobs.
*
* @return new {@link ThreadFactory} for creating daemon {@link Threads}
*/
public static ThreadFactory newDaemonThreadFactory() {
return new DaemonThreadFactory();
}
private static final class DaemonThreadFactory implements ThreadFactory {
static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
DaemonThreadFactory() {
SecurityManager s = System.getSecurityManager();
this.group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
this.namePrefix = "pool-" + poolNumber.getAndIncrement() + "-thread-";
}
public Thread newThread(Runnable r) {
Thread t =
new Thread(this.group, r,
this.namePrefix + this.threadNumber.getAndIncrement(), 0);
if (!t.isDaemon()) {
t.setDaemon(true);
}
/* optional */
if (t.getPriority() != Thread.MIN_PRIORITY) {
t.setPriority(Thread.MIN_PRIORITY);
}
return t;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment