Reputation: 4023
I try to code currently in Java 8. Yesterday I have found the next source with the examples from linear algebra. On the basis of the Matrix Vector multiplication (last example in the link) I coded my owner method for multiplication of matrices. My code is here:
import java.util.stream.IntStream;
public static void matrixMatrixProduct() {
System.out.println("Matrix matrix mulptiplication");
final int DIM1 = 15;
final int DIM2 = 20;
final int DIM3 = 2;
int[][] a = new int[DIM1][DIM2];
int[][] b = new int[DIM1][DIM3];
int[][] c = new int[DIM3][DIM2];
int counter = 1;
for (int i =0; i < DIM1; i++) {
for (int j =0; j < DIM3; j++) {
b[i][j] = counter++;
}
}
for (int i =0; i < DIM3; i++) {
for (int j =0; j < DIM2; j++) {
c[i][j] = counter++;
}
}
System.out.println("");
System.out.println("Print matrix b");
System.out.println("");
for (int i = 0; i < DIM1; i++) {
for (int j = 0; j < DIM3; j++) {
System.out.print(b[i][j] + " ");
}
System.out.print("\n");
}
System.out.println("");
System.out.println("Print matrix c");
System.out.println("");
for (int i = 0; i < DIM3; i++) {
for (int j = 0; j < DIM2; j++) {
System.out.print(c[i][j] + " ");
}
System.out.print("\n");
}
IntStream.range(0, DIM1)
.parallel()
.forEach( (i) -> {
IntStream.range(0, DIM2)
.sequential()
.forEach( (j) -> {
IntStream.range(0, DIM3)
.parallel()
.forEach( (k) -> {
a[i][j] += b[i][k]*c[k][j];
});
});
});
System.out.println("");
System.out.println("Print matrix a");
System.out.println("");
for (int i = 0; i < DIM1; i++) {
for (int j = 0; j < DIM2; j++) {
System.out.print(a[i][j] + " ");
}
System.out.print("\n");
}
My question is, what is exactly the difference between parallel()
and sequential()
method by the calling of IntStream
class? (Actually this is the most important part, where I do the multiplication explicitly). Based on this knowledge I want to know, what is a correct usage in the last IntStream
calling. Currently I have defined in this place the method parallel()
, but I'm not sure this is a right solution... Actually, if I change parallel()
to sequential()
I don't see any difference in the output.
Upvotes: 1
Views: 1081
Reputation: 836
Parallel operations happen concurrently. This means that the elements of the stream may be processed simultaneously.
Sequential operations happen one at a time.
Changing from sequential()
to parallel()
has no impact on the result since your operations are state-independent, but may affect your run-time. However, if the operations your perform affect future operations, then you should consider using sequential()
.
I would assume you want matrix operations to happen in parallel, but I'm not too familiar with the math.
Link to the Javadoc, as referenced by @the8472.
Upvotes: 1