Java Reference
In-Depth Information
* Use RecursiveTask<T> where, as in this example, each call returns
* a value that represents the computation for its subset of the overall task.
* @author Ian Darwin
*/
public
public class
class RecursiveTaskDemo
RecursiveTaskDemo extends
extends RecursiveTask < Long > {
private
private static
static final
final long
long serialVersionUID = 3742774374013520116L ;
static
static final
final int
int N = 10000000 ;
final
final static
static int
int THRESHOLD = 500 ;
int
int [] data ;
int
int start , length ;
public
public static
static void
void main ( String [] args ) {
int
int [] source = new
new int
int [ N ];
loadData ( source );
RecursiveTaskDemo fb = new
new RecursiveTaskDemo ( source , 0 , source . length );
ForkJoinPool pool = new
new ForkJoinPool ();
long
long before = System . currentTimeMillis ();
pool . invoke ( fb );
long
long after = System . currentTimeMillis ();
long
long total = fb . getRawResult ();
long
long avg = total / N ;
System . out . println ( "Average: " + avg );
System . out . println ( "Time :" + ( after - before ) + " mSec" );
}
static
static void
void loadData ( int
int [] data ) {
Random r = new
new Random ();
for
for ( int
int i = 0 ; i < data . length ; i ++) {
data [ i ] = r . nextInt ();
}
}
public
public RecursiveTaskDemo ( int
int [] data , int
int start , int
int length ) {
this
this . data = data ;
this
this . start = start ;
this
this . length = length ;
}
@Override
protected
protected Long compute () {
iif ( length <= THRESHOLD ) { // Compute Directly
long
long total = 0 ;
for
for ( int
int i = start ; i < start + length ; i ++) {
Search WWH ::




Custom Search