Skip to content

Instantly share code, notes, and snippets.

@plombardi89
Created September 7, 2014 18:27
Show Gist options
  • Save plombardi89/3f342c7171248aee1e95 to your computer and use it in GitHub Desktop.
Save plombardi89/3f342c7171248aee1e95 to your computer and use it in GitHub Desktop.
NamedThreadFactory in Java and Groovy style
import java.util.concurrent.ThreadFactory
import java.util.concurrent.atomic.AtomicInteger
// --- Java Style ---
class NamedThreadFactory implements ThreadFactory {
private final String prefix
private final AtomicInteger count
NamedThreadFactory(String prefix) {
if (!prefix?.trim()) {
throw new IllegalArgumentException("Cannot create $NamedThreadFactory without a base name. Provided prefix is: '$prefix'")
}
this.prefix = prefix
this.count = new AtomicInteger(0)
}
Thread newThread(Runnable runnable) {
new Thread(runnable, "${prefix}-${count.getAndIncrement()}")
}
}
def jtf = new NamedThreadFactory('foobar')
def jt = jtf.newThread { println 'Hello, world!' }
// --- Groovy Style ---
threadFactory = [
prefix : 'foobar',
count : new AtomicInteger(0),
newThread : { Runnable r -> new Thread(r, "${threadFactory.prefix}-${threadFactory.count.getAndIncrement()}") }
]
gtf = threadFactory as ThreadFactory
def gt = gtf.newThread { println 'Hello, world!' }
jt.start()
gt.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment