Created
September 7, 2014 18:27
-
-
Save plombardi89/3f342c7171248aee1e95 to your computer and use it in GitHub Desktop.
NamedThreadFactory in Java and Groovy style
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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