Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Forking and Joining Java to Maximize Multicore Power : Page 3

With JSR-166y, Java 7 will get a new way of structuring concurrent programming known as the fork/join framework. Find out how (and when) to use it.


advertisement

Moving On: Applying the Fork/Join Framework

The first step to using the fork/join framework is to create a ParallelArray instance around the data in question (the student array). To do so, the fork/join framework requires you to hook into the java.util.concurrent threading classes. Specifically, you need to create an Executor, and fortunately, the fork/join framework already provides one:

// . . . ForkJoinExecutor fjPool = new ForkJoinPool(25); // use 25 threads ParallelArray processor = ParallelArray.createUsingHandoff(currentClass, fjPool); // . . .

At this point, you have a ParallelArray and you can start fork/joining.



The first task is to rip through the array and list all of the students by their student ID number. Traditional Java would have you rip through the array item by item, sorting the current item into a results collection. Alternatively, you could use the Collections.sort() method to do the sorting, but that requires a Comparator-implementing class to do the actual comparison. As it turns out, writing that Comparator is pretty simple, and ParallelArray takes a Comparator to its sort() method:

// . . . System.out.println("Sorted by student ID:"); processor .sort(studentIDComparator) System.out.println(""); // . . . } private static final Comparator studentIDComparator = new Comparator() { public int compare(Student lhs, Student rhs) { if (lhs.studentID < rhs.studentID) return -1; else if (lhs.studentID > rhs.studentID) return 1; else return 0; } };

Notice how the studentIDComparator, rather than being passed in as an anonymous inner class instance right inline, is stored as a final reference in the class. This is a common pattern when working with the fork/join framework.

The results may be sorted at this point, but how can you tell? You need to display the results to the console. You could try to extract the results from the object returned from sort(), but there's an easier way. The ParallelArray class can take another Comparator-like object, again, either an anonymous inner class instance or stored final reference of the Ops.Procedure type, and call it on each element in the returned array:

// . . . System.out.println("Sorted by student ID:"); processor .sort(studentIDComparator) .apply(printOutStudent); System.out.println(""); // . . . } private static final Ops.Procedure printOutStudent = new Ops.Procedure() { public void op(Student s) { System.out.println("\t" + s); } };



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap