Are arrays thread-safe in Java?
I am not really sure if synchronizing only the write
method, while leaving the read
method unsychronized would work. Not really what are all the consequences, but at least it might lead to read
method returning some values that has just been overriden by write
.
While you will not get an invalid state by changing arrays as you mention, you will have the same problem that happens when two threads are viewing a non volatile integer without synchronization (see the section in the Java Tutorial on Memory Consistency Errors). Basically, the problem is that Thread 1 may write a value in space i, but there is no guarantee when (or if) Thread 2 will see the change.
The class java.util.concurrent.atomic.AtomicIntegerArray
does what you want to do.
The example has a lot of stuff that differs from the prose question.
The answer to that question is that distinct elements of an array are accessed independently, so you don't need synchronization if two threads change different elements.
However, the Java memory model makes no guarantees (that I'm aware of) that a value written by one thread will be visible to another thread, unless you synchronize access.
Depending on what you're really trying to accomplish, it's likely that java.util.concurrent
already has a class that will do it for you. And if it doesn't, I still recommend taking a look at the source code for ConcurrentHashMap
, since your code appears to be doing the same thing that it does to manage the hash table.