Java Reference
In-Depth Information
Java SE
In the Java SE landscape, a myriad of options have been introduced over the years. First, there's the
standard
java.lang.Thread
support present since day 1 and Java Development Kit (JDK) 1.0. Java 1.3
saw the introduction of
java.util.TimerTask
to support doing some sort of work periodically. Java 5
debuted the
java.util.concurrent
package as well as a reworked hierarchy for building thread pools,
oriented around the
java.util.concurrent.Executor
.
The application programming interface (API) for
Executor
is simple:
package java.util.concurrent;
public interface Executor {
void execute(Runnable command);
}
ExecutorService
, a subinterface, provides more functionality for managing threads and providing
support for raising events to the threads, such as
shutdown()
. There are several implementations that
have shipped with the JDK since Java SE 5.0. Many of them are available via static factory methods on
the
java.util.concurrent.Executors
class, in much the same way that utility methods for manipulating
java.util.Collection
instances are offered on the
java.util.Collections
class. What follows are
examples.
ExecutorService
also provides a
submit()
method, which returns a
Future<T>
. An instance of
Future<T>
can be used to track the progress of a thread that's executing—usually asynchronously. You
can call
isDone()
or
isCancelled()
to determine whether the job is finished or cancelled, respectively. If
you submit an object of type
Runnable
, whose primary method (
run
) supports no return type, the
get()
on Future<T>
method will return either
null
or a value that you specify as a parameter on submission of
the job, like so:
Runnable task = new Runnable(){
public void run(){
Thread.sleep( 1000 * 60 ) ;
System.out.println("Done sleeping for a minute, returning! " );
}
};
ExecutorService executorService = Executors.newCachedThreadPool() ;
if(executorService.submit(task, Boolean.TRUE).get().equals( Boolean.TRUE ))
System.out.println( "Job has finished!");
With that in hand, you can explore some the characteristics of the various implementations. For
example, you'll use the following
Runnable
instance:
package com.apress.springenterpriserecipes.spring3.executors;
import java.util.Date;
import org.apache.commons.lang.exception.ExceptionUtils;
public class DemonstrationRunnable implements Runnable {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(
ExceptionUtils.getFullStackTrace(e));
}
Search WWH ::
Custom Search