package savinov_roman_lab_1;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
import java.util.logging.Logger;

public class MergeSortForkJoinPool extends RecursiveAction {
    private static final int THRESHOLD = 1500;
    private static final ForkJoinPool pool = ForkJoinPool.commonPool();
    private static final Logger logger = Logger.getLogger(MergeSortForkJoinPool.class.getName());

    private final int[][] array;
    private final int left;
    private final int right;

    public MergeSortForkJoinPool(int[][] array, int left, int right) {
        this.array = array;
        this.left = left;
        this.right = right;
    }

    @Override
    protected void compute() {
        if (left >= right) return;

        if ((right - left + 1) <= THRESHOLD) {
            MergeSortThreadLess.mergeSort(array, left, right);
            return;
        }

        int middle = (left + right) / 2;

        logger.info("Создан поток: " + Thread.currentThread().getName());

        MergeSortForkJoinPool leftTask = new MergeSortForkJoinPool(array, left, middle);
        MergeSortForkJoinPool rightTask = new MergeSortForkJoinPool(array, middle + 1, right);

        invokeAll(leftTask, rightTask);
        MergeSortThreadLess.merge(array, left, middle, right);
    }

    public static void parallelSort(int[][] array) {
        pool.invoke(new MergeSortForkJoinPool(array, 0, array[0].length - 1));
    }
}
