There are several ways to do this.
Firstly, if you want the maximum concurrency to be a shared library, no matter how many threads access the matrix, and your int[][] is small enough, you can do this as follows.
- The
AtomicBoolean matrix AtomicBoolean is equal to the size of int[][] . - While you are trying to update the int matrix, first block
AtomicBoolean , use Unsafe.putIntVolatile() to update the value in a volatile way, and then reset AtomicBoolean .
Secondly, if you know the number of threads in advance.
- Store marker object / value according to stream, for example int; then create an additional int [] [] as a marker matrix. Initialize the marker matrix to some dummy value that is not equal to any of your stream marker values, for example. -1.
- While you are trying to update the int matrix, lock the cell in the thr marker matrix, using
Unsafe.compareAndSet() ; then update it Unsafe.putIntVolatile() ; and finally cancel the marker matrix to reset the value -1. A.
Finally, if you can tolerate int[][] , in fact this is not an int matrix in the actual code, then you can use the long[][] matrix, where the first 32 bits are the current number of updates for the value and the last 32 bits are the current value. Then you can easily use Unsafe.compareAndSet() to set this long value as a whole. Note that you can copy the upper 32-bit value, so you do not need to have the upper update limit == Integer.MAX_VALUE .
source share