ArrayList in java is thread safe.and it is implemented using array.
So, is the access to arrays in java thread safe??does the access to arrays needs to be synchronized??
ArrayList in java is thread safe.and it is implemented using array.
So, is the access to arrays in java thread safe??does the access to arrays needs to be synchronized??
No, ArrayList
isn't thread-safe in Java.
From the docs:
Note that this implementation is not synchronized. If multiple threads access an
ArrayList
instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally.
Are you thinking of Vector
, which uses synchronization internally? (Each method is synchronized, basically.)
What would a thread-safe array look like? You can't add or remove elements of an array. All you can do is assign values to individual members.
Suppose your code had
int x = a[2];
a[3] = x;
Is that thread safe? (Hint: possibly not, depends on how consistent you want a[2] and a[3] to be).
In general: start by being conspicuously thread-safe. Put the synchronization in - it's not so expensive. Really think about the semantics you mean. Test it and get the deadlocks out - if you have such problems you may well not have thought about what your are trying to do clearly enough. Only if your performance testing really shows this to be your bottleneck start to get clever.
Java memory models consider each array element as a separate variable. You may have thread-unsafe actions on such a variable just like any other variables.
The array itself is quite thread safe.
static Object[] a;
// thread 1
a = new Object[10];
// thread 2
read a.length // ok
read a[0] // ok
a[0] = something // ok
What's the big deal? If you use ArrayList for example, such actions are not safe without proper sync
static ArrayList a;
// thread 1
a = new ArrayList( another_collection_with_10_null );
// thread 2
a.size(); // unsafe
a.get(0); // unsafe
a.set(0, something); // unsafe
You may get incorrect results, or even unsensible results, or exceptions. You may complete screw up the list and make it permanently unusable.