MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Concurrent programming with Fork/Join framework in Java 7.0

In this article we will see some things about concurrent programming with Fork/Join framework in java 7.0

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

Language-level support for concurrent programming on the Java platform is very strong as proven by the efforts in different communities. The java communities are continuously comprehensive programming models and efficient implementations which abstracts the pain points associated with multi-threaded and distributed applications.

As we know java executor framework is the first concurrency framework available in java environment. The next step is the introduction of fork/join framework in java 7.0.

Before going into the details of fork/join framework, we need to understand the back ground a little, which has made this framework successful. For the last few years computer processors have improved their processing speed enormously. So the single threaded applications are also running much faster without any input from the developers end. Now, processor makers are also favoring multi-core chip designs. So the software has to be written in a multi-threaded or multi-process manner to take full advantage of the processor. As a result, concurrent programming is the only way to take full advantage of high speed multi-core processor.

Concurrent programming is a form of computation in which one big task is broken into many chunks and process simultaneously.”). As a result, if a CPU intensive big task can be divided in smaller, independent tasks, then those tasks can be assigned to different processor for fast processing. At the end of processing the processed chunks/tasks are merged together to get the end result.

From the discussion in the above two paragraphs, we can understand the importance of efficient concurrent programming. As the processors are improving and having multi-core facility, the application programming is also taking benefit by using frameworks like executor and fork/join.

The Java Fork/Join framework is designed based on divide-and-conquer algorithms. This type of algorithm is perfect for problems that can be divided into two or more sub tasks of the same type. Then recursion http://en.wikipedia.org/wiki/Recursion is used to break down the problem to simple tasks until they are simple enough to be solved directly. The solutions to the sub tasks are then combined or merged to give a solution to the original problem.

The Fork/Join Java framework originated as JSR-166. We can also use the related classes in JDK 1.5 and 1.6 without installing the latest JDK. For that, we have to download the jsr166 jar and launch our JVM using the option -Xbootclasspath/p: jsr166.jar. Note that you may need to precede “jsr166.jar” with its full file path because the JAR contains some classes that override the core Java classes.

The basic purpose of fork/join framework is to facilitate the concurrent processing environment in java applications. This fork/join framework is finer then the executor service framework. It takes the advantages of all processing power and hence the application gets more resource and process faster. It is an implementation of the ExecutorService interface that helps you take advantage of multiple processors. It is designed for tasks which can be broken into smaller pieces (of similar type) recursively and hence make the processing faster. The Fork/Join approach is similar to MapReduce. The only difference is that Fork/Join tasks will subdivide themselves into smaller tasks only if necessary (if too large), but MapReduce approach divides all the work into smaller pieces as the first step of their execution.

Similar to Executor framework, the fork/join framework also assign 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 can steal tasks from other threads that are still busy. The ForkJoinPoolclass is an extension of AbstractExecutorService and the heart of the framework. ForkJoinPool implements the core work-stealing algorithm and executes ForkJoinTasks.

Fork/Join Process

Showing how the work is divided into sub tasks and joined back to get the end result

Fork/Join Process

Figure 1: Fork/Join Process

The basic steps for implementing fork/join framework

  • Split the task
  • Assign it to the available threads
  • After completion join the chunks and make it complete

Following two diagrams shows CPU usage history for single thread and multiple thread applications.

You can observe that CPU usage is very low during the execution. It is always under utilized with single thread model execution.

CPU Usage

Figure 2: CPU Usage

You can observe that the CPU utilization is much better as all the processors contribute to the total calculation.

Better CPU Utilization

Figure 3: Better CPU Utilization

Now let us take an example to understand the concept in details.

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

Listing 1: Class showing the traditional way to do the task

package mrbool.com;
import java.util.Random;
// This class defines 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;
	}
}

Listing 2: Class performing the split and join task.

package mrbool.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() {
		if (list.length == 1) {
			result = list[0];
		} else {
			int midpoint = list.length / 2;
			int[] l1 = Arrays.copyOfRange(list, 0, midpoint);
			int[] 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;
		}
	}
}

Listing 3: Class invoking the ForkJoinExecutor pool to perform the task.

package mrbool.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);		
	}
}

Conclusion:

In this article we have gone through the parallel programming features in the Java platform through its evolution from Single threaded model to executor framework and the Fork/Join framework introduced in Java7. Java executors (known as executor framework) were a major improvement made to the Java platform in Java 5 but their calls are blocking in nature. This is where the Fork/Join framework introduced in Java7 and it plays a vital role to solve the issue. The fork/join framework provides a very straightforward and efficient structure to solve concurrent programming issues. This article also explained with a very simple example the concurrent and parallelism programming concepts. This is only the surfaces of fork/join framework.There are numerous other features exists and are ready to help you leveraging the multi-cores CPUs. This is a new era which is emerging, so developers should get familiar with these concepts.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?

Did you like the post?

Help us to keep publishing good contents like this.

SUPPORT US

funded

remaining

[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login