Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java array thread safety

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??

like image 529
userv Avatar asked Aug 24 '26 04:08

userv


2 Answers

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.)

like image 178
Jon Skeet Avatar answered Aug 25 '26 19:08

Jon Skeet


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.

like image 37
djna Avatar answered Aug 25 '26 19:08

djna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!