Java Reference
In-Depth Information
9
// class that stores two Instants in time
10
class
TimeData
11
{
12
public
Instant start;
13
public
Instant end;
14
15
// return total time in seconds
16
public double
timeInSeconds()
17
{
18
return
Duration.between(start, end).toMillis() /
1000.0
;
19
}
20
}
// end class TimeData
21
22
public class
FibonacciDemo
23
{
24
public static void
main(String[] args)
25
throws
InterruptedException, ExecutionException
26
{
27
// perform synchronous fibonacci(45) and fibonacci(44) calculations
28
System.out.println(
"Synchronous Long Running Calculations"
);
29
TimeData synchronousResult1 = startFibonacci(45);
TimeData synchronousResult2 = startFibonacci(44);
30
31
double
synchronousTime =
32
calculateTime(synchronousResult1, synchronousResult2);
33
System.out.printf(
34
" Total calculation time = %.3f seconds%n"
, synchronousTime);
35
36
// perform asynchronous fibonacci(45) and fibonacci(44) calculations
37
System.out.printf(
"%nAsynchronous Long Running Calculations%n"
);
38
CompletableFuture<TimeData> futureResult1 =
CompletableFuture.supplyAsync(() -> startFibonacci(
45
));
CompletableFuture<TimeData> futureResult2 =
CompletableFuture.supplyAsync(() -> startFibonacci(
44
));
39
40
41
42
43
// wait for results from the asynchronous operations
44
TimeData asynchronousResult1 = futureResult1.get();
TimeData asynchronousResult2 = futureResult2.get();
45
46
double
asynchronousTime =
47
calculateTime(asynchronousResult1, asynchronousResult2);
48
System.out.printf(
49
" Total calculation time = %.3f seconds%n"
, asynchronousTime);
50
51
// display time difference as a percentage
52
String percentage = NumberFormat.getPercentInstance().format(
53
synchronousTime / asynchronousTime);
54
System.out.printf(
"%nSynchronous calculations took %s"
+
55
" more time than the asynchronous calculations%n"
, percentage);
56
}
57
58
// executes function fibonacci asynchronously
59
private static
TimeData startFibonacci(
int
n)
60
{
Fig. 23.30
|
Fibonacci calculations performed synchronously and asynchronously. (Part 2 of 4.)