Skip to content

Instantly share code, notes, and snippets.

/Pool.java Secret

Created March 1, 2015 03:22
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/1e8de4e6a5d112cc8815 to your computer and use it in GitHub Desktop.
Save anonymous/1e8de4e6a5d112cc8815 to your computer and use it in GitHub Desktop.
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