1

I have a multi-threaded program where multiple threads are accessing and editing my data structure; My data structure is is CopyOnWriteArrayList. Since the CopyOnWriteArrayList is a part of the Java Concurrent package, do I still have to wrap the data structure in a Synchronized block when I perform a modification operation on it ?

Tony
  • 33
  • 2

2 Answers2

1

The answer depends on the architecture of your program. You can build a program entirely out of "thread-safe" classes, but that will not necessarily make your application "thread-safe."

You need synchronization whenever you have a thread that can not do its work without putting data into a temporarily invalid state. In order to make it work, you must synchronize the routine that creates the temporary invalid state, and you must also synchronize every routine that could possibly see the state.

So, the question is, Is there any moment in the execution of your program when one thread could put that CopyOnWriteArrayList into a state that you would not want another thread to see? (Either because its contents are internally inconsistent, or because it is inconsistent with some other data structure).

If the answer is Yes, then you still need synchronization.

Solomon Slow
  • 25,130
  • 5
  • 37
  • 57
0

No, you don't have to:

A thread-safe variant of ArrayList in which all mutative operations (add, set, and so on) are implemented by making a fresh copy of the underlying array.

Depending on how often you are modifying your data, the CopyOnWriteArrayList might not be the best option, though. See this StackOverflow question for some potential alternatives.

Community
  • 1
  • 1
Marvin
  • 13,325
  • 3
  • 51
  • 57
  • Thank you for the reply, I update my data very often. What would you suggest as a better option ? – Tony Jan 07 '16 at 15:21
  • @Tony: I added a link to a related question. Without knowing your code I can't really suggest anything in particular. – Marvin Jan 07 '16 at 18:55