Skip to content

Instantly share code, notes, and snippets.

/Pool.java Secret

Created Mar 1, 2015
Embed
What would you like to do?
package me.creatures.util;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author Septron
* @since February, 28
*/
public class Pool {
public static Pool singleton;
static {
singleton = new Pool();
}
private final ThreadFactory factory = new ThreadFactory() {
private final AtomicInteger count = new AtomicInteger();
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setName(String.format("Worker-%d", count.getAndIncrement()));
return thread;
}
};
public final ExecutorService executor = Executors.newCachedThreadPool(factory);
}
class Example implements Callable<Boolean> {
public static void main(String... args) throws Exception {
Future<Boolean> a = Pool.singleton.executor.submit(new Example(true));
// Do other stuff
// ...
// Gets the value of the submitted method... (Will wait if it needs to)
if (a.get()) {
System.out.println("Hello world from thread " + Thread.currentThread().getName());
}
Pool.singleton.executor.shutdown();
}
private final boolean stuff;
public Example(final boolean stuff) {
this.stuff = stuff;
}
@Override
public Boolean call() throws Exception {
System.out.println("Hello world from thread " + Thread.currentThread().getName());
return stuff;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment