Skip to content
TheChatArchiveThe Chat Archive
gpt-4-1106-preview· openaiHugging Face Suzhen/CodeChat

Write a java code to parallel computing for Matrix multiplication

  1. User

    Write a java code to parallel computing for Matrix multiplication

  2. Assistant

    Parallel computing in Java for matrix multiplication can be achieved using Threads or the modern ExecutorService framework. Here we will use ExecutorService and Callables to demonstrate parallel processing for matrix multiplication.

    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    
    public class MatrixMultiplication {
    
        // Method to multiply two matrices
        public static double[][] multiplyMatrices(double[][] matrix1, double[][] matrix2) {
            int matrix1Rows = matrix1.length;
            int matrix1Cols = matrix1[0].length;
            int matrix2Cols = matrix2[0].length;
            
            double[][] result = new double[matrix1Rows][matrix2Cols];
            List<Future<Void>> tasks = new ArrayList<>();
            
            ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    
            for (int row = 0; row < matrix1Rows; row++) {
                for (int col = 0; col < matrix2Cols; col++) {
                    tasks.add(executorService.submit(new MatrixMultiplicationTask(matrix1, matrix2, result, row, col)));
                }
            }
            
            for (Future<Void> task : tasks) {
                try {
                    task.get(); // Wait and get the result of the computation
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }
            }
            
            executorService.shutdown();
            return result;
        }
    
        // Callable class for parallel computation of matrix multiplication
        public static class MatrixMultiplicationTask implements Callable<Void> {
            private double[][] matrix1;
            private double[][] matrix2;
            private double[][] result;
            private int row;
            private int col;
    
            public MatrixMultiplicationTask(double[][] matrix1, double[][] matrix2, double[][] result, int row, int col) {
                this.matrix1 = matrix1;
                this.matrix2 = matrix2;
                this.result = result;
                this.row = row;
                this.col = col;
            }
    
            @Override
            public Void call() {
                result[row][col] = 0;
                for (int k = 0; k < matrix2.length; k++) {
                    result[row][col] += matrix1[row][k] * matrix2[k][col];
                }
                return null;
            }
        }
    
        public static void main(String[] args) {
            double[][] matrix1 = {{1, 2}, {3, 4}};
            double[][] matrix2 = {{5, 6}, {7, 8}};
    
            double[][] result = multiplyMatrices(matrix1, matrix2);
    
            // Print the result matrix
            for (double[] row : result) {
                for (double value : row) {
                    System.out.print(value + " ");
                }
                System.out.println();
            }
        }
    }
    

    This example code defines a MatrixMultiplication class with a method multiplyMatrices that multiplies two matrices in parallel. The MatrixMultiplicationTask implements Callable<Void> and is responsible for calculating a single element of the result matrix.

    The matrix multiplication computation is divided into smaller tasks that are submitted to an ExecutorService. Each task computes a single element of the result matrix using a pair of nested for-loops.

    After submitting all the tasks, we wait for all of them to complete and then we can safely access the result matrix. Remember to shutdown the ExecutorService once all work has been completed and resources are no longer needed.

    The main method demonstrates how the multiplyMatrices method can be used to multiply two matrices.

    Please note that matrix multiplication requires the number of columns in the first matrix to be equal to the number of rows in the second matrix. The provided code doesn't check for this condition, so you may want to include validation before attempting to multiply matrices.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.