Skip to content

Instantly share code, notes, and snippets.

@andrask
Created January 23, 2013 15:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save andrask/4608603 to your computer and use it in GitHub Desktop.
Save andrask/4608603 to your computer and use it in GitHub Desktop.
Example for ExecutorService in Java
package aa;
import java.text.MessageFormat;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class Pooling {
private static final int NUMBER_OF_THREADS = 3;
public static void main(String[] args) {
final ExecutorService executor = Executors.newFixedThreadPool(NUMBER_OF_THREADS);
for (int i = 0; i < 10; i++) {
// Work items will be executed in an indeterministic order in the available threads.
// At most NUMBER_OF_THREADS work items will be executed at the same time.
executor.execute(createWorkItemWithOrderNumber(i));
}
}
static final AtomicInteger concurrentExecutions = new AtomicInteger(0);
private static Runnable createWorkItemWithOrderNumber(final int orderNumber) {
return new Runnable() {
@Override
public void run() {
int numberOfConcurrentExecutions = concurrentExecutions.incrementAndGet();
System.out.println(MessageFormat.format("This is the {0}th work item running in thread {1}, # of concurrent executions {2}",
orderNumber, Thread.currentThread().getName(), numberOfConcurrentExecutions));
concurrentExecutions.decrementAndGet();
}
};
}
// Output will be similar to this:
// This is the 0th work item running in thread pool-1-thread-1
// This is the 2th work item running in thread pool-1-thread-3
// This is the 4th work item running in thread pool-1-thread-3
// This is the 3th work item running in thread pool-1-thread-1
// This is the 5th work item running in thread pool-1-thread-3
// This is the 6th work item running in thread pool-1-thread-1
// This is the 7th work item running in thread pool-1-thread-3
// This is the 8th work item running in thread pool-1-thread-1
// This is the 9th work item running in thread pool-1-thread-3
// This is the 1th work item running in thread pool-1-thread-2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment