views:

71

answers:

3

Hi all, i just have a quick question about concurrent programming in Java. for example, i have a NxN matrix, and there is a corresponding thread for each row of the matrix, if there is no interaction between threads in each row, is it safe (or correct) if multiple threads access and modify separate rows of the matrix simultaneously? Thanks!!

A: 

If you have a native 2d array, and not a wrapper class, then concurrent row access should be fine. As long as you never read/write or write/write to the same memory location, you're okay.

Stefan Kendall
+2  A: 

If you are only doing reads of the matrix, it is always safe. If you are doing writes, but a thread only reads and writes to the row it is assigned, it is safe. It is only if you have a thread reading from a cell written by another thread that you have to worry about locks.

unholysampler
The only problem might be the "master thread" the OP is talking about in the comment: if this thread reads values, these might not be current.
hstoerr
You are right, while master thread is accessing the treemap, there is no guarantee that others are not doing R/W. i will take care of this and make sure there are no slaves accessing the treemap while master is in.
I just have one more question.if multiple threads are accessing the treemap within a synchronized method at the same time, and the master thread is waiting to access the treemap in another synchronized method. what will happen if there is one thread left the first method, will the lock be returned and visible to master thread, or master thread only can see the lock until the last thread left from first synchronized method.
The order in which threads waiting to access a monitor will get that access is unspecified, and the correctnes of your program should not depend on it.
Tuure Laurinolli
A: 

Provided you can guarantee no thread will mutate any element that any other thread reads or mutates, and also that no thread will change the dimensions of the matrix, this should be safe.

moonshadow