0

I have a question about simple ArrayList, not synchronizedList or CopyOnWriteArrayList. It is possible to use them with multiple threads that add and get elements in safe manner, using synchronization block or method?? And if yes: at that point what is the difference between a simple ArrayList with synchronized block and a synchronizedList?

Mohamad Shiralizadeh
  • 8,329
  • 6
  • 58
  • 93
Beruth
  • 13
  • 1
  • 6

2 Answers2

0

Yes, it is possible to use an ArrayList by multiple threads using synchronized blocks or methods properly. In fact, it you check the source code of the Collections.synchronizedList(), it does the same. If you use the same object for synchronized methods or blocks for every type of access (get, add, iterate etc.), it is ok.

Basri Kahveci
  • 391
  • 3
  • 7
0

You can use almost every class in a multi-threaded program if you guard access to it properly. After all, it would be impractical up to impossible to make every piece of code thread-safe, so applications have to implement thread safety on a higher level instead.

This is even the case when using the result of synchronizedList. This list will synchronize every method call but algorithms requiring more than one call will break without additional synchronization, including the simple

if(!list.contains(x)) {
    list.add(x);
}

as there might be a concurrent update in-between these two method invocations (this is called the check-then-act anti-pattern).

So the difference between using synchronized blocks with an ArrayList and using the result of Collections.synchronizedList(new ArrayList<>()) is that the synchronizedList will apply synchronization on every method invocation which will be insufficient as soon as an operation is composed of multiple invocations, while manual synchronized blocks provide you full control over when to synchronize and which code range will be covered and are necessary anyway even if you use Collections.synchronizedList

Holger
  • 285,553
  • 42
  • 434
  • 765