Reputation: 503
i want to increase +1 the numbers inside a row of matrix using threads.
what i wrote is that (only the shared resource method):
public void increaseRow(Integer row) {
if (!mapForRow.containsKey(row))
mapForRow.put(row, "not increased");
if (mapForRow.get(row).equals("not increased")) {
lock.lock();
try {
while (rowIncreased) {
condition.await();
}
mapForRow.get(row).equals("increased");
rowIncreased = true;
for (int j = 0; j < matrix.length; j++)
setMatrix(row, j, matrix[row][j] + 1);
rowIncreased = false;
// replace the value
mapForRow.get(row).equals(" not increased");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println();
System.out.println("begin print matrix");
for (int i = 0; i < row; i++) {
System.out.println();
for (int j = 0; j < column; j++)
System.out.print(matrix[i][j]);
}
System.out.println();
System.out.println("end print matrix ");
System.out.println();
lock.unlock();
condition.notifyAll();
}
}
}
the matrix is initialized with 10 rows and 10 columns and the threads started are also 10
but via output i' m getting this:
begin print matrix
0000000000
0000000000
0000000000
0000000000
end print matrix
begin print matrix
00Exception in thread "Thread-0" 00000000
0000000000
0000000000
end print matrix
java.lang.IllegalMonitorStateException
[...]
i can understand the the thrown exception, but why the matrix is not fully displayed?
Upvotes: 1
Views: 47
Reputation: 1723
Why don't you use an AtomicInteger
for that. These can be safely accessed and manipulated from multiple threads without the need of locking.
If you imagine your code as in between the lines starting with //
, you can see that, the NullPointerException
will be caught and handled while the lock is in place, but if any other exception is thrown, one that is not caught in that block, the exception will progress up the stack trace until caught, and when it is caught, you lock will long have been released.
try {
// start of your code
lock.lock();
try {
doStuff();
} catch(InterruptedException e) {
System.out.println("in lock");
} finally {
lock.unlock();
}
// end of your code
} catch(Exception e) { // IllegalMonitorStateException caught here
System.out.println("not in lock");
}
Upvotes: 2