Dhirendra Gautam
Dhirendra Gautam

Reputation: 857

Why there is requirement of Thread safe collection?

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.

Upvotes: 3

Views: 144

Answers (2)

Solomon Slow
Solomon Slow

Reputation: 27210

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.

Upvotes: 0

Thilo
Thilo

Reputation: 262850

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

Upvotes: 3

Related Questions