-7

Why the ArrayList class in Java doesn't implemented with thread safety. But prior class Vector is implemented with thread safety ? Is there any particular reason for not implementing with thread safe ?

Satheesh M
  • 221
  • 2
  • 7
  • 3
    The Java developers decided that having thread-safety compulsorarily baked into standard container types was not a good idea. – khelwood Jul 23 '19 at 07:57
  • There is a (performance) cost to thread-safety that you don't want to force on everyone that does not need it. Also, if you do need it, a simple solution like synchronizing all methods (as in Vector) may not be enough for you anyway. – Thilo Jul 23 '19 at 07:58
  • My question is not how to make thread safe. My question is clearly on why its not implemented in that way as because its prior class is implemented using it – Satheesh M Jul 23 '19 at 07:59

1 Answers1

1

Taken from Why is Java Vector (and Stack) class considered obsolete or deprecated?


Vector synchronizes on each individual operation. That's almost never what you want to do.

Generally you want to synchronize a whole sequence of operations. Synchronizing individual operations is both less safe (if you iterate over a Vector, for instance, you still need to take out a lock to avoid anyone else changing the collection at the same time, which would cause a ConcurrentModificationException in the iterating thread) but also slower (why take out a lock repeatedly when once will be enough)?

Of course, it also has the overhead of locking even when you don't need to.

Basically, it's a very flawed approach to synchronization in most situations. As Mr Brian Henk pointed out, you can decorate a collection using the calls such as Collections.synchronizedList - the fact that Vector combines both the "resized array" collection implementation with the "synchronize every operation" bit is another example of poor design; the decoration approach gives cleaner separation of concerns.

Thilo
  • 257,207
  • 101
  • 511
  • 656
  • It is worth mentioning (in relation to the performance argument) that if the JVM (for Java 6+) can determine by escape analysis that the synchronization is unnecessary, it isn't used. But clearly that only applies in situations where that can be determined. – Andy Turner Jul 23 '19 at 08:10