Java Reference

In-Depth Information

(
a
)equalsthenumberofrowsinthesecond
Matrix
(
b
),whichisessentialtotheal-

gorithm,
multiply()
creates a
Matrix
named
result
and enters a sequence of

nested loops to perform the multiplication.

The essence of these loops is as follows: For each row in
a
, multiply each of that

row'scolumnvaluesbythecorrespondingcolumn'srowvaluesin
b
.Addtogetherthe

resultsofthemultiplications,andstoretheoveralltotalin
result
atthelocationspe-

cified via the row index (
i
) in
a
and the column index (
j
) in
b
.

When you run this application, it generates the following output, which indicates

thata1-row-by-3-columnmatrixmultipliedbya3-row-by-2columnmatrixresultsina

1-row-by-2-column matrix:

1.0 2.0 3.0

4.0 7.0

5.0 8.0

6.0 9.0

32.0 50.0

Computer scientists classify this algorithm as O(n
3
), which is read “big-oh of n-

cubed”or“approximatelyn-cubed.”Thisnotationisanabstractwayofclassifyingthe

algorithm'sperformance(withoutbeingboggeddowninspecificdetailssuchasmicro-

processorspeed).AO(n
3
)classificationindicatesverypoorperformance,andthisper-

formance worsens as the sizes of the matrixes being multiplied increase.

The performance can be improved (on multiprocessor and/or multicore platforms)

by assigning each row-by-column multiplication task to a separate thread-like entity.

Listing 6-9
showsyouhowtoaccomplish thisscenario inthecontext oftheFork/Join

Framework.

Listing 6-9.
Multiplying two matrixes via the Fork/Join Framework

import java.util.ArrayList;

import java.util.List;

import java.util.concurrent.ForkJoinPool;

import java.util.concurrent.RecursiveAction;

class MatMult extends RecursiveAction

{