Java Reference
In-Depth Information
additionaltasksaresubmittedwhenallthreadsareactive,theywaitinthequeueforan
available thread.
If any thread terminates because of a failure during execution before the executor
shutsdown,anewthreadwilltakeitsplacewhenneededtoexecutesubsequenttasks.
Thethreadsinthepoolwillexistuntiltheexecutorisexplicitlyshutdown.Thismethod
throws IllegalArgumentException when you pass zero or a negative value to
nThreads .
Note Threadspoolsareusedtoeliminatetheoverheadfromhavingtocreateanew
threadforeachsubmittedtask.Threadcreationisnotcheap,andhavingtocreatemany
threads could severely impact an application's performance.
Youwouldcommonlyuseexecutors,runnables,callables,andfuturesinaninput/out-
putcontext.(IdiscussJava'ssupportforfilesysteminput/outputin Chapter8 . )Perform-
ing a lengthy calculation offers another scenario where you could use these types. For
example, Listing6-1 usesanexecutor,acallable,andafutureinacalculationcontextof
Euler's number e (2.71828…).
Listing 6-1. Calculating Euler's number e
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class CalculateE
{
final static int LASTITER = 17;
public static void main(String[] args)
{
ExecutorService
executor
=
Execut-
ors.newFixedThreadPool(1);
Callable<BigDecimal> callable;
callable = new Callable<BigDecimal>()
Search WWH ::




Custom Search