DemoFibonacciCalc.java

/*
 * Copyright 2024 Hochschule Luzern Informatik.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ch.hslu.exercises.sw11.ex3.fibo;

import org.slf4j.LoggerFactory;
import org.slf4j.Logger;

import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * Codevorlage für die Verwendung von RecursiveTask mit einem Fork-Join-Pool.
 */
public final class DemoFibonacciCalc {

    private static final Logger LOG = LoggerFactory.getLogger(DemoFibonacciCalc.class);

    /**
     * Privater Konstruktor.
     */
    private DemoFibonacciCalc() {
    }

    /**
     * Berechnet den Fibonacci Wert für n.
     *
     * @param n für die Fibonacci Berechnung.
     * @return Resultat der Fibonacci Berechnung.
     */
    public static long fiboIterative(final int n) {
        long f = 0;
        long g = 1;
        for (int i = 1; i <= n; i++) {
            f = f + g;
            g = f - g;
        }
        return f;
    }

    /**
     * Berechnet den Fibonacci Wert für n.
     *
     * @param n für die Fibonacci Berechnung.
     * @return Resultat der Fibonacci Berechnung.
     */
    public static long fiboRecursive(final int n) {
        return n > 1 ? fiboRecursive(n - 1) + fiboRecursive(n - 2) : n;
    }

    /**
     * Main-Demo.
     *
     * @param args not used.
     */
    public static void main(final String[] args) throws InterruptedException {
        //cold
//        fiboRecursive(10);
//
//        IntStream.of(25, 30, 42).forEach(DemoFibonacciCalc::executeFibonacciCalculation);
//
//        new Thread(() -> {
//            try {
//                System.out.println(1 / 0);
//            } catch (Exception e) {
//                System.out.println("Error");
//            }
//        }).start();
//
//        Thread.sleep(2000);
//        System.out.println("fertig");
        List<Thread> threads = new ArrayList<>();
        IntStream.range(0, 500).forEach(i -> {
            Thread thread = new Thread(() -> System.out.println(i));
            thread.start();
            threads.add(thread);
        });
        threads.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        Thread.sleep(2000);

    }


    private static void executeFibonacciCalculation(final int n) {
        Duration duration;
        long start;
        long stop;
        long result;

        LOG.info("fibo({}) start...", n);

        start = System.currentTimeMillis();
        result = fiboRecursive(n);
        stop = System.currentTimeMillis();
        duration = Duration.ofMillis(stop - start);
        LOG.info("Func. recursive = {}", result);
        LOG.info("Func. recursive : {} msec.", duration.toMillis());

        FibonacciTask task = new FibonacciTask(n);
        start = System.currentTimeMillis();
        result = task.invoke();
        stop = System.currentTimeMillis();
        duration = Duration.ofMillis(stop - start);
        LOG.info("Conc. CommonPool recursive = {}", result);
        LOG.info("Conc. CommonPool recursive : {} msec.", duration.toMillis());


        try (final ForkJoinPool pool = new ForkJoinPool()) {
            task = new FibonacciTask(n);
            start = System.currentTimeMillis();
            result = pool.invoke(task);
            stop = System.currentTimeMillis();
            duration = Duration.ofMillis(stop - start);
            LOG.info("Conc. ForkJoinPool recursive = {}", result);
            LOG.info("Conc. ForkJoinPool recursive : {} msec.", duration.toMillis());
        }


        start = System.currentTimeMillis();
        result = fiboIterative(n);
        stop = System.currentTimeMillis();
        duration = Duration.ofMillis(stop - start);
        LOG.info("Func. iterative = {}", result);
        LOG.info("Func. iterative : {} msec.", duration.toMillis());

        LOG.info("fibo({}) ended...\n\n", n);
    }
}