I have many byte arrays of size 4096 (16x16x16), and I want editing them from many threads in one time, there is small chance that any element will be written in one time by more than one thread, and almost impossible that more than 3 will be accessing it (one of elements) in one time (write or read).
But whole array can be accessed by many threads in one time.
Can this cause any problems? If yes, then how to fix/avoid them?
I know that reading should be safe, and I hear about some problems with writing
Code need be fast (real-time based stuff) so I can't synchronize that, and I can't use any ArrayList, because that will cause problems with memory. (There will be like 1000-20000 (or even more) arrays like that)
-
116x16x16 = 4096, not 65536.rgettman– rgettman2015-02-25 19:55:38 +00:00Commented Feb 25, 2015 at 19:55
-
What behavior do you expect from your array when multiple threads are trying to write into the same cell? Here surely can be a problemesin88– esin882015-02-25 20:11:29 +00:00Commented Feb 25, 2015 at 20:11
-
oh, It actually should be 4096, I was thinking about other part of code, sorry.GotoFinal– GotoFinal2015-02-25 20:12:39 +00:00Commented Feb 25, 2015 at 20:12
-
@esin88 Yeach, that can be a problem, but, there is very small chance that 2 thread will write to this same cell (but array can be edited by more than one), so it can even "choose" random operation. Why there is no AtomicByteArray?GotoFinal– GotoFinal2015-02-25 20:18:18 +00:00Commented Feb 25, 2015 at 20:18
-
Why would you need that? Array write operation must be atomic by itself. Of course if you dont do anything else after writing. Although if you expect to see changes made by one thread from another thread, that wouldn't workesin88– esin882015-02-25 20:23:21 +00:00Commented Feb 25, 2015 at 20:23
1 Answer
Every time someone says real time in the same sentence as Java it peaks my interest because real time has a specific meaning that most people don't understand ( oracle / sun have a real time jvm available for purchase )
But I digress , array reads and writes are atomic, therefore thread safe. 2 threads cannot write to the array at the same time because the operation cannot get broken down to anything smaller ( allowing a scheduler to interrupt halfway through ) As long as you are careful ( e.g. Are not reading a value, doing some math and then writing it back to the array and expecting the the value at the given index to remain the same )
So in short there is nothing stopping you from doing this as long as your logic around it is also thread safe.