What is Fork/Join framework in java 7.0 (Parallel programming)?

Fork/Join framework has been introduced in java 7 to solve multi-threading/parallel programming issues.

It is very difficult to deal with concurrent (parallel) programming by using traditional way. Because you have to deal with thread synchronization, notification, приєднатися і т.д., а також підводні камені загальних ресурсів,,en,Підтримка мови рівня для паралельного програмування на платформі Java дуже сильна, як доведено зусилля в різних громадах,,en,Ці спільноти все намагалися забезпечити комплексні програмні моделі та ефективні реалізації, абстрагують больові точки, пов'язані з багатопотокової і розподіленої applications.Java платформою,,en,стандартне видання,,en,Java SE,,es,а потім Java SE,,en,представила набір пакетів,,en,виконавець послуг,,en,забезпечуючи потужний паралелізм будівельних блоків,,en,подальше розширення рамок, додавши більше опори для паралельності,,en,Вилка / Join являє собою нову концепцію в Java,,en,Основна мета цієї структури полягає в сприянні багатопотокової середовища в Java-додатку,,en,Чим дрібніше то рамка виконавця послуг є вилка / намалюйте рамки,,en. language-level support for concurrent programming on the Java platform is very strong as proven by the efforts in different communities. These communities all tried to provide comprehensive programming models and efficient implementations that abstracts the pain points associated with multi-threaded and distributed applications.Java Platform, Standard Edition (Java SE) 5 and then Java SE 6 introduced a set of packages (Executor service)providing powerful concurrency building blocks. Java SE 7 further enhanced the framework adding more supports for parallelism.

Fork/Join is a new concept in java 7.0 version. The basic purpose of this framework is to facilitate the multithreading environment in java applications. The finer then the executor service framework is fork/join framework. It takes the advantages of all processing power and hence the application gets more resource and processing power. It is an implementation of the ExecutorService interface that helps you take advantage of multiple processors. It is designed for works which can be broken into smaller pieces recursively and hence make the processing faster.

Similar to ExecutorService, the fork/join framework also distributes tasks to worker threads in a thread pool. But the main difference is that the fork/join framework uses a work-stealing algorithm. Here the worker threads that run out of things to do can steal tasks from other threads that are still busy. The ForkJoinPoolclass is an extension of AbstractExecutorService and the heart of the framework. ForkJoinPool реалізує основний алгоритм роботи крадіжки і виконує ForkJoinTasks,,en,Тепер дозвольте мені взяти приклад, щоб зрозуміти цю концепцію в деталях,,en,Основні кроки,,en,розділити завдання,,en,Призначають його в доступних потоків,,en,Після завершення приєднатися шматки і зробити його завершення,,en,Візьмемо список, який буде містити велику кількість цілих чисел, що генеруються випадковим чином,,en,Цей клас показує традиційний спосіб зробити задачу,,en,Тепер наступний клас SplitTask виконує розкол і об'єднати завдання,,en,захищений недійсним обчислення,,en,list.length ==,,en,результат = список,,en,ІНТ середина = list.length,,en,l1 = Arrays.copyOfRange,,en,список,,en,середня точка,,en,l2 = Arrays.copyOfRange,,ar,list.length,,en,SplitTask s1 = новий SplitTask,,en,L1,,st,SplitTask s2 = новий SplitTask,,en,l2,,ar,forkJoin,,no,s2,,ja,Результат = s1.result,,en,s2.result,,en,Останній клас тестування процесу,,en.
Now let me take an example to understand the concept in details.

The basic steps are
· Split the task
· Assign it to the available threads
· After completion join the chunks and make it complete

Let us take a list which will contain large number of integers generated at random.

This class is showing the traditional way to do the task.

package javablog.levent.com;
import java.util.Random;
// This class defins a list which will contain large number of integers.
public class LargeInteger {
private final int[] list = new int[2000000];
public largeInteger() {
Random generator = new Random(19580427);
for (int i = 0; i < list.length; i++) {
list[i] = generator.nextInt(500000);
}
}
public int[] getList() {
return list;
}
}

Now the following SplitTask class is performing the split and join task.

package javablog.levent.com;
import java.util.Arrays;
import jsr166y.forkjoin.RecursiveAction;
public class SplitTask extends RecursiveAction {
private int[] list;
public long result;
public SplitTask(int[] array) {
this.list = array;
}

@ Override
protected void compute() {
якщо (list.length == 1) {
result = list[0];
} else {
int midpoint = list.length / 2;
десяткового[] l1 = Arrays.copyOfRange(list, 0, midpoint);
десяткового[] l2 = Arrays.copyOfRange(list, midpoint, list.length);
SplitTask s1 = new SplitTask(l1);
SplitTask s2 = new SplitTask(l2);
forkJoin(s1, s2);
result = s1.result + s2.result;
}
}
}

The last class is testing the process. Він виклик ForkJoinExecutor пулу для виконання завдання,,en,Вилка / Join рамки,,en.

package javablog.levent.com;
import jsr166y.forkjoin.ForkJoinExecutor;
import jsr166y.forkjoin.ForkJoinPool;
import javablog.levent.com.SplitTask;
public class TestForkJoin {
public static void main(String[] args) {
LargeInteger test = new LargeInteger();
// Check the number of available processors
int nThreads = Runtime.getRuntime().availableProcessors();
System.out.println(nThreads);
SplitTask mfj = new SplitTask(test.getList());
ForkJoinExecutor pool = new ForkJoinPool(nThreads);
pool.invoke(mfj);
long result = mfj.getResult();
System.out.println("Done. Result: " + result);

}
}

============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share