2

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)

10
  • 1
    16x16x16 = 4096, not 65536. Commented 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 problem Commented Feb 25, 2015 at 20:11
  • oh, It actually should be 4096, I was thinking about other part of code, sorry. Commented 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? Commented 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 work Commented Feb 25, 2015 at 20:23

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.