I had a 2×2 array that I had two threads operating on.
it is possible to use a synchronized statement in java on an array?
how does the locking work? the java tutorial thread said that the synchronized statement works on objects, so I wasn’t sure what they meant. Another site said that I could make a statement like
synchronized (array1[]){
}
Does this synchronize accesses to everything in the array so that the array is locked to other threads?
if I have a two-d Array can i use
synchronized (array1[i]) to lock one of the rows of the array?
and is it possible to lock individual array values
with something like
synchronized (array1[i][j]){
}
But yeah, tips or help are greatly appreciated. Actually I already turned it in, correct or not. But I want to know for future use
Yes, you can synchronize using an array as monitor object, because arrays (even arrays of primitives) are objects in Java.
You can synchronize a block of code on a specific monitor like this:
It is best practice to synchronize as few lines of code as possible.
Synchronizing code on a monitor does not affect the monitor in any way, it only affects the threads accessing the synchronized block of code. Before thread execution can enter the block of code, it must obtain ‘the lock’ on the monitor. The Java runtime ensures that at most one thread at a time can have ‘the lock’ on a monitor. So synchronizing on your array does not prohibit unsynchronized blocks of code to access it! The trick is to make sure that all the operations you don’t want to happen at the same time are within blocks synchronized on the same monitor.
Since Java does not offer multi-dimensional arrays, only arrays-of-arrays, you can certainly synchronize on a nested array for more fine-grained synchronization. If you model a 2d array as an array of rows, you can only synchronize on rows, not on columns because in that example columns are not represented as separate arrays.
You can only synchronize on single array values if these are non-primitve, so Integer() instead of int. Note that Integer() is an immutable object, so you would not be able to change its value. A solution would be to create your own Cell() wrapper object with a getter and setter for the contained numeric value. This would allow you to let a thread get a lock on the Cell and safely change its value.
Because it’s my day off I decided to have some fun and created a working example of what you describe. Yes, this is my idea of having fun.
Classes:
The application starts multiple operations on the same matrix. The only synchronized block of code is in the class Operation. If you remove the synchronization, the results will be wrong because two operations are manipulating the same row simultaneously.
Output when synchronized:
Example output when NOT synchronized:
Note that I added some Thread.sleep() statements in the operation implementations to make the difference between synchronized and unsynchronized execution more obvious.