3

Why we need a thread-safe collection if we easily convert a non-thread-safe collection to Thread safe.

Ex: we can create Synchronized ArrayList by using Collections.synchronizedList() method.

Kalamarico
  • 5,466
  • 22
  • 53
  • 70
Dhirendra Gautam
  • 737
  • 8
  • 16
  • Because sometimes you do not want to synchronize each time you access a list or, wait for someone to finish reading\writing. Take a look, f.e. at `java.util.concurrent.CopyOnWriteArrayList`. – Pavel Smirnov Jul 25 '19 at 08:28
  • 1
    `Collections.synchronizedList` blocks all other threads from accessing that list. The contention may be unacceptable. – Andy Turner Jul 25 '19 at 08:29
  • 2
    It's also important to note that `Collections.synchronizedList` is thread safe with respect to its internal properties. It does not necessarily mean that your code will be thread-safe by using it. – Andy Turner Jul 25 '19 at 08:33

2 Answers2

3
  • synchronizedList just wraps all methods with exclusive locks. That may be too strict for you. For example, you may very well want to allow any number of concurrent read operations to proceed at the same time (and only serialize writes). A specialized implementation can offer that.

  • synchronizedList is only thread-safe in the sense that its internal state does not get corrupted. That may not be enough for your application. For example if (list.isEmpty()) list.add(1); is not thread-safe even on a synchronized list. Nor is for (String x: list) giving you a snapshot iteration. Specialized implementations can add higher-level atomic operations.

Thilo
  • 257,207
  • 101
  • 511
  • 656
0

Why we need a thread-safe collection...

You don't need them, because, as you have pointed out,

we can create Synchronized ArrayList by using Collections.synchronizedList() method.

So why does the library provide "concurrent" collection classes? It's because some of those classes can be implemented using thread-safe algorithms, and especially, non-blocking algorithms that may be more efficient or safer than using a mutex-protected algorithm.

Of course, as others have pointed out, simply protecting a collection might not always be enough for your application. You might need a mutex anyway to protect some other data that is related to the collection.

But, if the lock-free versions are helpful to you, then the good news is that they are there; and if they are not helpful, then the good news is that you don't have to use them.

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