Java Reference
In-Depth Information
Calculation time for fibonacci(44) = 3.605 seconds
Total calculation time = 9.506 seconds
Asynchronous Long Running Calculations
Calculating fibonacci(45)
Calculating fibonacci(44)
fibonacci(44) = 701408733
Calculation time for fibonacci(44) = 3.650 seconds
fibonacci(45) = 1134903170
Calculation time for fibonacci(45) = 5.911 seconds
Total calculation time = 5.911 seconds
Synchronous calculations took 161% more time than the asynchronous ones
Fig. 23.30
|
Fibonacci calculations performed synchronously and asynchronously. (Part 4 of 4.)
Class
TimeData
Class
TimeData
(lines 10-20) stores two
Instant
s representing the start and end time of
a task, and provides method
timeInSeconds
to calculate the total time between them. We
use
TimeData
objects throughout this example to calculate the time required to perform
Fibonacci calculations.
Method
startFibonacci
for Performing and Timing Fibonacci Calculations
Method
startFibonacci
(lines 59-70) is called several times in
main
(lines 29, 30, 39 and
41) to initiate Fibonacci calculations and to calculate the time each calculation requires.
The method receives the Fibonacci number to calculate and performs the following tasks:
•
Line 62 creates a
TimeData
object to store the calculation's start and end times.
•
Line 64 displays the Fibonacci number to be calculated.
•
Line 65 stores the current time before method
fibonacci
is called.
•
Line 66 calls method
fibonacci
to perform the calculation.
•
Line 67 stores the current time after the call to
fibonacci
completes.
•
Line 68 displays the result and the total time required for the calculation.
•
Line 69 returns the
TimeData
object for use in method
main
.
Performing Fibonacci Calculations Synchronously
Method
main
(lines 24-56) first demonstrates synchronous Fibonacci calculations. Line
29 calls
startFibonacci(45)
to initiate the
fibonacci(45)
calculation and store the
TimeData
object containing the calculation's start and end times. When this call com-
pletes, line 30 calls
startFibonacci(44)
to initiate the
fibonacci(44)
calculation and
store its
TimeData
. Next, lines 31-32 pass both
TimeData
objects to method
calculate-
Time
(lines 91-104), which returns the total calculation time in seconds. Lines 33-34 dis-
play the total calculation time for the synchronous Fibonacci calculations.
Performing Fibonacci Calculations Asynchronously
Lines 38-41 in
main
launch the asynchronous Fibonacci calculations in separate threads.
CompletableFuture
static
method
supplyAsync
executes an asynchronous task that re-
turns a value. The method receives as its argument an object that implements interface
Sup-