|
|
Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs
Page 4 of 6
At some point, you'll want to obtain an executor. The Executor framework supplies the Executors utility class for this purpose. Executors offers several factory methods for obtaining different kinds of executors that offer specific thread-execution policies.
Here are three examples:
nThreads threads are actively processing tasks. If additional tasks are submitted when all threads are active, they wait in the queue
until a thread is available. If any thread terminates through failure during execution before shutdown, a new thread will
be created to take its place when subsequent tasks need to be executed. The pool's threads exist until the executor is shut
down.
The Executor framework offers additional types (such as the ScheduledExecutorService interface), but the types you are likely to work with most often are ExecutorService, Future, Callable, and Executors.
See the java.util.concurrent Javadoc to explore additional types.
You'll find that the Executor framework is fairly easy to work with. In Listing 2, I've used Executor and Executors to replace the server example from Listing 1 with a more scalable thread pool-based alternative.
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
class Server
{
static Executor pool = Executors.newFixedThreadPool(5);
public static void main(String[] args) throws IOException
{
ServerSocket socket = new ServerSocket(9000);
while (true)
{
final Socket s = socket.accept();
Runnable r = new Runnable()
{
@Override
public void run()
{
doWork(s);
}
};
pool.execute(r);
}
}
static void doWork(Socket s)
{
}
}
Listing 2 uses newFixedThreadPool(int) to obtain a thread pool-based executor that reuses five threads. It also replaces new Thread(r).start(); with pool.execute(r); for executing runnable tasks via any of these threads.
Listing 3 presents another example in which an application reads the contents of an arbitrary web page. It outputs the resulting lines or an error message if the contents aren't available within a maximum of five seconds.
Using the Java Concurrency Utilities -- more tutorials on JavaWorld:
java.util.concurrent to work around deadlock and similar threading pitfalls.
CountDownLatch and Executors.newFixedThreadPool concurrency utilities.
java.util.concurrent classes were used to optimize thread use for faster performance in a real-world application.
ExecutorService class with ForkJoinPool in a web crawler.
Popular articles in the Java 101 series