Frank Cunningham
Frank Cunningham

Reputation: 178

how to make thread-safe row matrix in java

I have a problem: I have a structure that represent a matrix of int. I have to do some operation on single row of this matrix and that operations have to be thread safe. I thought of lock the entire matrix but I want to lock only the single line. How can I do that??? thx

Upvotes: 0

Views: 1353

Answers (2)

Java does not actually support multidimensional arrays natively. A 2D array is simply an array of arrays.

Therefore, you could synchronize on a single row:

synchronized(matrix[row_index]) {
    // do stuff with matrix[row_index] here
}

This is assuming no other code reassigns matrix[row] (the array itself, not the elements); if it can, then you need a temporary variable to avoid the race condition where another thread might reassign it in the middle of your synchronized block:

int[] the_row = matrix[row_index];
synchronized(the_row) {
    // do stuff with the_row here (NOT matrix[row_index])
}

Alternatively, you could use a separate array of lock objects:

// a field in your Matrix class
Object[] row_locks;

// initialized like this (probably in your constructor, or whenever the matrix is resized)
for(int row_index = 0; row_index < number_of_rows; row_index++)
    row_locks[row_index] = new Object();

// and used like this:
synchronized(row_locks[row_index]) {
    // do stuff with the row_index'th row here
}

Upvotes: 3

kechap
kechap

Reputation: 2087

You have to keep an array to store the row number that is currently busy. Each time you will access a row you will have to call a function that populates this array in order to prevent others to access the same row. If you finish working on the a specific row you will delete the row number from the array to make it accessible for others again.

Upvotes: -2

Related Questions