From 508d412a1a0dc7d7e20664b1e200f2cd2e598a7a Mon Sep 17 00:00:00 2001 From: LordBaryhobal Date: Tue, 17 Dec 2024 15:28:34 +0100 Subject: [PATCH] added ex Q2 --- .../ex_q2/CustomRecursiveAction.java | 34 +++++++++++++++++++ src/exercises/ex_q2/ForkJoinTest.java | 28 +++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 src/exercises/ex_q2/CustomRecursiveAction.java create mode 100644 src/exercises/ex_q2/ForkJoinTest.java diff --git a/src/exercises/ex_q2/CustomRecursiveAction.java b/src/exercises/ex_q2/CustomRecursiveAction.java new file mode 100644 index 0000000..0c89b79 --- /dev/null +++ b/src/exercises/ex_q2/CustomRecursiveAction.java @@ -0,0 +1,34 @@ +package exercises.ex_q2; + +import java.util.concurrent.RecursiveAction; +import java.util.logging.Logger; + +public class CustomRecursiveAction extends RecursiveAction { + private static final int threshold = 10; + private String song; + + public CustomRecursiveAction(String song) { + this.song = song; + } + + @Override + protected void compute() { + Logger logger = Logger.getAnonymousLogger(); + if (song.length() <= threshold) { + logger.info("Splitting problem"); + changeToUppercase(); + } else { + logger.info("Problem is small enough"); + int halfSize = song.length() / 2; + CustomRecursiveAction task1 = new CustomRecursiveAction(song.substring(0, halfSize)); + CustomRecursiveAction task2 = new CustomRecursiveAction(song.substring(halfSize)); + invokeAll(task1, task2); + song = task1.song + task2.song; + logger.info("Solution: " + song); + } + } + + protected void changeToUppercase() { + song = song.toUpperCase(); + } +} diff --git a/src/exercises/ex_q2/ForkJoinTest.java b/src/exercises/ex_q2/ForkJoinTest.java new file mode 100644 index 0000000..7d80f0e --- /dev/null +++ b/src/exercises/ex_q2/ForkJoinTest.java @@ -0,0 +1,28 @@ +package exercises.ex_q2; + +import java.util.concurrent.ForkJoinPool; + +public class ForkJoinTest { + public static void main(String[] args) { + String song = "Georges Brassens (1964) - Les Copains d'abord" + + "Non, ce n'était pas le radeau" + + "De la Méduse, ce bateau" + + "Qu'on se le dise au fond des ports" + + "Dise au fond des ports" + + "Il naviguait en père peinard" + + "Sur la grand-mare des canards" + + "Et s'appelait les Copains d'abord" + + "Les Copains d'abord"; + int processors = Runtime.getRuntime().availableProcessors(); + System.out.println("Number of available processors: " + processors); + ForkJoinPool pool = new ForkJoinPool(processors); + long startTime = System.currentTimeMillis(); + pool.invoke(new CustomRecursiveAction(song)); + long endTime = System.currentTimeMillis(); + System.out.println( + "Fork/Join tasks took " + + (endTime - startTime) + + " milliseconds." + ); + } +} \ No newline at end of file