Using the Fork/join framework provided by JAVA7

Source: Internet
Author: User

In Java7, the JDK provides a very powerful framework for multithreaded development, which is the Fork/join framework. This is for the original executors more

Furthermore, a work-stealing strategy is added on the basis of the computation of parallel divide and conquer, which means. When a thread is waiting for him to create

When a child thread runs, the current thread, if it finishes its task, looks for tasks that are not yet running and runs them.

Executors the biggest difference in this way, the more efficient use of thread resources and functionality. So it is highly recommended to use the Fork/join framework.


Let's use an example to illustrate how the framework is used, mainly by creating a list of 10,000 resources to modify his content.


Package com.bird.concursey.charpet8;/** * Store, the name and price of a product * @author Bird October 7, 2014 PM 11:23:14 */pub Lic class Product {private String name;private double price;public string getName () {return name;} public void SetName (String name) {this.name = name;} Public double GetPrice () {return price;} public void Setprice (double price) {this.price = Price;}}


Package Com.bird.concursey.charpet8;import java.util.arraylist;import java.util.list;/** * Generate a List of random Products * @author Bird * October 7, 2014 PM 11:24:47 */public class Productlistgenerator {public list<product> generate (i NT size) {list<product> List = new arraylist<product> (); for (int i = 0; i < size; i++) {Product Product = N EW product ();p roduct.setname ("product" + i);p Roduct.setprice (ten); List.add (product);} return list;}}


Package Com.bird.concursey.charpet8;import Java.util.list;import Java.util.concurrent.forkjoinpool;import Java.util.concurrent.recursiveaction;import Java.util.concurrent.timeunit;public class Task extends RecursiveAction {private static final long Serialversionuid = 1l;//These attributes would determine the block of products this task have to process.private list<product> products;private int first;private int last;//Store the increment of the price of The productsprivate double increment;public Task (list<product> products, int first, int. last, double increment) {sup ER (); this.products = Products;this.first = First;this.last = Last;this.increment = increment;} /** * If The difference between the last and first attributes are greater than * or equal to ten, create the new Task object  s, one to process the first * half of products and the other to process the second half and execute * them in Forkjoinpool Using the InvokeAll () method. */@Overrideprotected void Compute () {if (LASt-first <) {updateprices ();} else {int middle = (first + last)/2; System.out.printf ("Task:pending tasks:%s\n", Getqueuedtaskcount ()); Task T1 = new Task (products, first, middle + 1, increment); Task t2 = new Task (products, middle + 1, last, increment); InvokeAll (t1, T2);}} private void UpdatePrices () {for (int i = First, i < last; i++) {Product Product = Products.get (i);p roduct.setprice (pro Duct.getprice () * (1 + increment));}} public static void Main (string[] args) {productlistgenerator productlistgenerator = new Productlistgenerator (); List<product> products = Productlistgenerator.generate (10000); Task task = new Task (products, 0, products.size (), 0.2); Forkjoinpool pool = new Forkjoinpool ();p ool.execute (Task);d o {System.out.printf ("Main:thread Count:%d\n", Pool.getactivethreadcount ()); System.out.printf ("Main:thread Steal:%d\n", Pool.getstealcount ()); System.out.printf ("Main:parallelism:%d\n", pool.getparallelism ()); try {TimeUnit.MILLISECONDS.sleep (5);} catch ( InterrupTedexception e) {e.printstacktrace ();}} while (!task.isdone ());p Ool.shutdown (), if (task.iscompletednormally ()) {System.out.printf ("main:the process has Completed normally.\n ");} for (product product:products) {if (Product.getprice ()! =) {System.out.printf ("Product%s:%f\n", Product.getname (), Product.getprice ());}} System.out.println ("Main:end of the Program.\n");}


in this example created a Forkjoinpool object and a subclass of the
Forkjointask class that you execute the pool. To create the Forkjoinpool object,
You are used the constructor without arguments, so it would be executed with its default
Configuration. It creates a pool with a number of threads equal to the number of processors
of the computer. When the Forkjoinpool object was created, those threads is created and
They wait in the pool until some tasks arrive for their execution.
Since the Task class doesn ' t return a result, it extends the Recursiveaction class. In the
recipe, you are used the recommended structure for the implementation of the task. If the
task has to update more than, it divides those set of elements into, blocks,
creates , and assigns a block to each task. You are used the first and last
attributes in the Task class to know the range of positions, the this task had to UPDA Te in the
List of products. You are used the first and last attributes to use only one copy of the
products list and not create different lists fo R each task.
To execute the subtasks a task creates, it calls the InvokeAll () method. This is a
Synchronous call, and the task waits for the finalization of the subtasks before continuing
(potentially finishing) its execution. While the task was waiting for its subtasks, the worker thread
That is executing it takes another task that is waiting for execution and executes it. With
This behavior, the Fork/join framework offers a more efficient task management than the
Runnable and callable objects themselves.

the InvokeAll () method of the Forkjointask class is one of the main differences
between th e Executor and the Fork/join framework. The Executor framework, all the tasks
has the to is sent to the Executor, and while in this case, the tasks include methods To execute and
control the tasks inside the pool. You had used the InvokeAll () method in the Task class,
that extends the Recursiveaction class that extends the Forkjoi Ntask class.
Sent a unique task to the pool to update all the list of products using the Execute ()
Method. In this case, it's a asynchronous call, and the main thread continues its execution.
You are used some methods of the Forkjoinpool class to check the status and the
Evolution of the tasks that is running. The class includes more methods so can be useful
For this purpose. See the monitoring a fork/join pool recipe for a complete list of
Those methods.
Finally, like with the Executor framework, you should finish Forkjoinpool using the
Shutdown () method.

Using the Fork/join framework provided by JAVA7

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.