Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Introduction of Fork/Join Framework Mechanism in Java

Shulou Source: shulou.com Published: 2022-06-02 07:18:47 10月18日 Update

This article mainly explains "the introduction of Fork/Join framework mechanism in Java". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "the introduction of Fork/Join framework mechanism in Java".

I. Fork/Join framework

Java provides a Fork/Join framework for parallel execution of tasks. The core idea is to divide a large task into multiple small tasks, and then summarize the execution results of each small task to get the final result of the large task.

This mechanism strategy is very common in distributed databases, where the data is distributed in different database replicas. When executing a query, each service has to run a query task and finally do data merging on one service, or provide an intermediate engine layer to summarize the data:

Core process: split tasks, module tasks are executed asynchronously, and single task results are merged; in programming, there is not much common code, but general ideas can be seen everywhere.

Second, core API and method 1, coding case

A calculation case based on 1-2... 100 demonstrates the basic use of the Fork/Join framework.

Import java.util.concurrent.ForkJoinPool;import java.util.concurrent.ForkJoinTask;import java.util.concurrent.RecursiveTask;public class ForkJoin01 {public static void main (String [] args) {int [] numArr = new int [100]; for (int I = 0; I < 100; iTunes +) {numArr [I] = I + 1;} ForkJoinPool pool = new ForkJoinPool () ForkJoinTask forkJoinTask = pool.submit (new SumTask (numArr, 0, numArr.length)); System.out.println ("merge result:" + forkJoinTask.invoke ()); pool.shutdown () }} / * * Thread task * / class SumTask extends RecursiveTask {/ * * threshold for segmenting task blocks * if THRESHOLD=100 * output: main [summation: (0.100) = 5050] merge calculation result: 5050 * / private static final int THRESHOLD=100; private int arr []; private int start; private int over Public SumTask (int [] arr, int start, int over) {this.arr = arr; this.start = start; this.over = over;} / / Sum calculation private Integer sumCalculate () {Integer sum = 0; for (int I = start; I < over; iTunes +) {sum + = arr [I] } String task = "[summation: (" + start + "..." + over + ") =" + sum + "]"; System.out.println (Thread.currentThread (). GetName () + task); return sum;} @ Override protected Integer compute () {if ((over-start))

Tags: Tasks threads data queues results frameworks cores mechanisms data sources states algorithms different valid addresses subclasses that is situations validity periods permissions cases Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS vpn Apple MySQL Huawei