Java Reference

In-Depth Information

plish meaningful work,
RecursiveAction
's
void compute()
method is over-

ridden.

Note
Although
compute()
isnormallyusedtosubdivideataskintosubtasksre-

cursively,I'vechosentohandlethemultiplicationtasksomewhatdifferently(forbrev-

ity and simplicity).

c
andinstantiates
ForkJoinPool
.Ittheninstantiates
MatMult
,passingthesethree

Matrix
instancesasargumentstothe
MatMult(Matrix a, Matrix b, Mat-

rix c)
constructor,andcalls
ForkJoinPool
's
T invoke(ForkJoinTask<T>

task)
method to start running this initial task. This method does not return until the

initial task and all of its subtasks complete.

The
MatMult(Matrix a, Matrix b, Matrix c)
constructorinvokesthe

MatMult(Matrix a, Matrix b, Matrix c, int row)
constructor,spe-

cifying
-1
as
row
's value. This value is used by
compute()
, which is invoked as a

resultoftheaforementioned
invoke()
methodcall,todistinguishbetweentheinitial

task and subtasks.

When
compute()
is initially called (
row
equals
-1
), it creates a
List
of

MatMult
tasks and passes this
List
to
RecursiveAction
's
Collection<T>

invokeAll(Collection<T> tasks)
method (inherited from

ForkJoinTask
).This method forksall the
List
collection's tasks, which will start

to execute. It then waits until the
invokeAll()
method returns (which also joins to

allthesetasks),whichhappenswhenthe
boolean isDone()
method(alsoinherited

from
ForkJoinTask
) returns true for each task.

Noticethe
tasks.add(new MatMult(a, b, c, row));
methodcall.This

call assigns a specific
row
value to a
MatMult
instance. When
invokeAll()
is

called, each task's
compute()
method is called and detects a different value (other

than -1) assigned to
row
. It then executes
multiplyRowByColumn(a, b, c,

row);
for its specific
row
.

When you run this application (
java MatMult
), it generates the following output:

1.0 2.0 3.0

4.0 5.0 6.0

7.0 1.0