I am trying to achieve matrix multiplication using the concept of concurrency and cyclic barrier.
Here is the code snippet:-
import Jama.Matrix;
public class Application {
public final CyclicBarrier cyclicBarrier;
public Matrix A = new Matrix(200,120);
public Matrix B = new Matrix(120,100);
public Matrix C = new Matrix(200,100);
public Application() {
initializeMatrix(A,A.getRowDimension(),A.getColumnDimension());
initializeMatrix(B,B.getRowDimension(),B.getColumnDimension());
cyclicBarrier = new CyclicBarrier(4, new Runnable() {
@Override
public void run() {
display(C);
}
});
new Thread(new Task(50,25)).start();
new Thread(new Task(100,50)).start();
new Thread(new Task(150,75)).start();
new Thread(new Task(200,100)).start();
}
public void initializeMatrix(Matrix X,int row,int col){
for (int i=0;i<row;i++)
for (int j=0;j<col;j++)
X.set(i,j,Math.random());
}
public void Multiply(int rowend, int col){
for (int i=0;i<rowend;i++){
for (int j=0;j<col;j++){
double sum = 0;
for (int k=0;k<B.getRowDimension();k++){
sum += A.get(i,k)*B.get(k,j);
}
C.set(i,j,sum);
}
}
display(C);
}
public void display(Matrix X){
System.out.print("C = [");
for (int i=0;i<X.getRowDimension();i++){
for (int j=0;j<X.getColumnDimension();j++){
System.out.print(X.get(i,j) + ",");
}
System.out.println();
}
System.out.print(" ]\n\n");
}
private class Task implements Runnable{
int row = 0;
int col = 0;
public Task(int row, int col){
this.row = row;
this.col = col;
}
@Override
public void run() {
Multiply(row, col);
try {
cyclicBarrier.await();
} catch (InterruptedException iex) {
System.out.println(iex.getMessage());
} catch (BrokenBarrierException bbex) {
System.out.println(bbex.getMessage());
}
}
}
public static void main(String args[]) {
new Application();
}
}
The need of concurrency in this is that the Matrix are huge and I need to do the computation fast. Is this the correct way of doing it? and Can I optimize it further?