O'Reilly logo

Java Pocket Guide by Patricia Liguori, Robert Liguori

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Concurrent Utilities

Java 2 SE 5.0 introduced utility classes for concurrent programming. These utilities reside in the package java.util.concurrent, and they include executors, concurrent collections, synchronizers, and timing utilities.

Executors

The class ThreadPoolExecutor as well as its subclass ScheduledThreadPoolExecutor implement the Executor interface to provide configurable, flexible thread pools. Thread pools allow server components to take advantage of the reusability of threads.

The class Executors provides factory (object creator) methods and utility methods. Of them, the following are supplied to create thread pools:

newCachedThreadPool()

Creates an unbounded thread pool that automatically reuses threads

newFixedThreadPool(int nThreads)

Creates a fixed-size thread pool that automatically reuses threads off a shared unbounded queue

newScheduledThreadPool(int corePoolSize)

Creates a thread pool that can have commands scheduled to run periodically or on a specified delay

newSingleThreadExecutor()

Creates a single-threaded executor that operates off an unbounded queue

newSingleThreadScheduledExecutor()

Creates a single-threaded executor that can have commands scheduled to run periodically or by a specified delay

The following example demonstrates usage of the newFixedThreadPool factory method:

	import java.util.concurrent.Executors;
	import java.util.concurrent.ExecutorService; public class ThreadPoolExample { public static void main( ) { // Create tasks // (from 'class ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required