Yes, you can synchronize the use of an array as a monitor object, because arrays (even arrays of primitives) are objects in Java.
You can synchronize the code block on a specific monitor as follows:
public void myMethod() { unsynchronized_statements... synchronized(myMonitorObject) { synchronized_statments... }
It’s best to sync as few lines of code as possible.
The synchronization of the code on the monitor does not affect the monitor in any way, it only affects the threads accessing the synchronized block of code. Before a thread can enter a code block, it must receive a “lock” on the monitor. Java runtime ensures that no more than one thread at a time can have a "lock" on the monitor. Thus, synchronization on your array does not prohibit unsynchronized blocks of code from accessing it! The trick is to make sure that all operations that you do not want to perform at the same time are in blocks synchronized to the same monitor.
Since Java does not offer multidimensional arrays, only arrays of arrays, you can, of course, synchronize with a nested array for finer synchronization. If you model a 2d array as an array of rows, you can only synchronize rows, not columns, because in this example, columns are not represented as separate arrays.
You can only synchronize values of one array if they are not primitve, therefore Integer () instead of int. Please note that Integer () is an immutable object, so you cannot change its value. The solution would be to create your own Cell () shell object using getter and setter for the contained numeric value. This will allow you to allow the thread to obtain a lock in the cell and safely change its value.
Since it was my day off, I decided to have fun and created a working example of what you described. Yes, it is my idea to have fun.
Classes:
The application starts several operations with the same matrix. The only synchronized code block is in the Operation class. If you delete synchronization, the results will be erroneous, because two operations simultaneously process the same line.
Sync output:
[105, 104, 103, 102, 101] [110, 109, 108, 107, 106] [115, 114, 113, 112, 111] [120, 119, 118, 117, 116] [125, 124, 123, 122, 121] [130, 129, 128, 127, 126] [135, 134, 133, 132, 131] [140, 139, 138, 137, 136] [145, 144, 143, 142, 141] [150, 149, 148, 147, 146]
Example output in the absence of synchronization:
[105, 4, 103, 102, 101] [110, 9, 108, 207, 106] [115, 14, 113, 212, 111] [120, 19, 118, 217, 116] [125, 124, 123, 122, 121] [130, 129, 128, 127, 126] [135, 34, 133, 232, 131] [140, 139, 138, 137, 136] [145, 144, 143, 142, 141] [150, 149, 148, 147, 146]
Note that I have added some Thread.sleep () statements in the implementation of the operations to make the difference between synchronized and unsynchronized execution more obvious.