View Javadoc
1   /*
2    * Copyright 2024 Hochschule Luzern Informatik.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package ch.hslu.exercises.sw11.ex3.fibo;
17  
18  import org.slf4j.LoggerFactory;
19  import org.slf4j.Logger;
20  
21  import java.time.Duration;
22  import java.time.Instant;
23  import java.util.ArrayList;
24  import java.util.List;
25  import java.util.concurrent.ExecutorService;
26  import java.util.concurrent.Executors;
27  import java.util.concurrent.ForkJoinPool;
28  import java.util.concurrent.Future;
29  import java.util.stream.IntStream;
30  import java.util.stream.Stream;
31  
32  /**
33   * Codevorlage für die Verwendung von RecursiveTask mit einem Fork-Join-Pool.
34   */
35  public final class DemoFibonacciCalc {
36  
37      private static final Logger LOG = LoggerFactory.getLogger(DemoFibonacciCalc.class);
38  
39      /**
40       * Privater Konstruktor.
41       */
42      private DemoFibonacciCalc() {
43      }
44  
45      /**
46       * Berechnet den Fibonacci Wert für n.
47       *
48       * @param n für die Fibonacci Berechnung.
49       * @return Resultat der Fibonacci Berechnung.
50       */
51      public static long fiboIterative(final int n) {
52          long f = 0;
53          long g = 1;
54          for (int i = 1; i <= n; i++) {
55              f = f + g;
56              g = f - g;
57          }
58          return f;
59      }
60  
61      /**
62       * Berechnet den Fibonacci Wert für n.
63       *
64       * @param n für die Fibonacci Berechnung.
65       * @return Resultat der Fibonacci Berechnung.
66       */
67      public static long fiboRecursive(final int n) {
68          return n > 1 ? fiboRecursive(n - 1) + fiboRecursive(n - 2) : n;
69      }
70  
71      /**
72       * Main-Demo.
73       *
74       * @param args not used.
75       */
76      public static void main(final String[] args) throws InterruptedException {
77          //cold
78  //        fiboRecursive(10);
79  //
80  //        IntStream.of(25, 30, 42).forEach(DemoFibonacciCalc::executeFibonacciCalculation);
81  //
82  //        new Thread(() -> {
83  //            try {
84  //                System.out.println(1 / 0);
85  //            } catch (Exception e) {
86  //                System.out.println("Error");
87  //            }
88  //        }).start();
89  //
90  //        Thread.sleep(2000);
91  //        System.out.println("fertig");
92          List<Thread> threads = new ArrayList<>();
93          IntStream.range(0, 500).forEach(i -> {
94              Thread thread = new Thread(() -> System.out.println(i));
95              thread.start();
96              threads.add(thread);
97          });
98          threads.forEach(t -> {
99              try {
100                 t.join();
101             } catch (InterruptedException e) {
102                 throw new RuntimeException(e);
103             }
104         });
105         Thread.sleep(2000);
106 
107     }
108 
109 
110     private static void executeFibonacciCalculation(final int n) {
111         Duration duration;
112         long start;
113         long stop;
114         long result;
115 
116         LOG.info("fibo({}) start...", n);
117 
118         start = System.currentTimeMillis();
119         result = fiboRecursive(n);
120         stop = System.currentTimeMillis();
121         duration = Duration.ofMillis(stop - start);
122         LOG.info("Func. recursive = {}", result);
123         LOG.info("Func. recursive : {} msec.", duration.toMillis());
124 
125         FibonacciTask task = new FibonacciTask(n);
126         start = System.currentTimeMillis();
127         result = task.invoke();
128         stop = System.currentTimeMillis();
129         duration = Duration.ofMillis(stop - start);
130         LOG.info("Conc. CommonPool recursive = {}", result);
131         LOG.info("Conc. CommonPool recursive : {} msec.", duration.toMillis());
132 
133 
134         try (final ForkJoinPool pool = new ForkJoinPool()) {
135             task = new FibonacciTask(n);
136             start = System.currentTimeMillis();
137             result = pool.invoke(task);
138             stop = System.currentTimeMillis();
139             duration = Duration.ofMillis(stop - start);
140             LOG.info("Conc. ForkJoinPool recursive = {}", result);
141             LOG.info("Conc. ForkJoinPool recursive : {} msec.", duration.toMillis());
142         }
143 
144 
145         start = System.currentTimeMillis();
146         result = fiboIterative(n);
147         stop = System.currentTimeMillis();
148         duration = Duration.ofMillis(stop - start);
149         LOG.info("Func. iterative = {}", result);
150         LOG.info("Func. iterative : {} msec.", duration.toMillis());
151 
152         LOG.info("fibo({}) ended...\n\n", n);
153     }
154 }