Java Reference
In-Depth Information
Tip
Increasetheprecisionaswellas
LASTITER
'svaluetoconvergetheseriestoa
lengthier and more accurate approximation of e.
call()
nextinitializesa
java.math.BigDecimal
localvariablenamed
res-
ult
to
BigDecimal.ZERO
. It then enters a loop that calculates a factorial, divides
BigDecimal.ONE
by the factorial, and adds the division result to
result
.
The
divide()
methodtakesthe
MathContext
instanceasitssecondargumentto
ensurethatthedivisiondoesnotresultina
nonterminating decimal expansion
(thequo-
tient result of the division cannot be represented exactly—0.3333333…, for example),
whichthrows
java.lang.ArithmeticException
(toalertthecallertothefact
thatthequotientcannotberepresentedexactly),whichtheexecutorrethrowsas
Exe-
cutionException
.
When you run this application, you should observe output similar to the following:
waiting
waiting
waiting
waiting
2.71828182845904507051604779584860506117897963525103269890073500406522504250484331405588797434
4245741730039454062711
Synchronizers
TheThreadingAPIofferssynchronizationprimitivesforsynchronizingthreadaccessto
criticalsections.Becauseitcanbedifficulttocorrectlywritesynchronizedcodethatis
based on these primitives, the concurrency utilities include synchronizers, classes that
facilitate common forms of synchronization.
Five commonly used synchronizers are countdown latches, cyclic barriers, ex-
changers, phasers, and semaphores:
• A
countdown latch
lets one or more threads wait at a “gate” until another
thread opens this gate, at which point these other threads can continue. The
java.util.concurrent.CountDownLatch
classimplementsthissyn-
chronizer.
• A
cyclic barrier
letsagroupofthreadswaitforeachothertoreachacommon
barrier point
.The
java.util.concurrent.CyclicBarrier
classim-
plements this synchronizer, and makes use of the
java.util.concurrent.BrokenBarrierException
class.
Cyc-