Why doesn't Collections.Generic.Queue have Synchronized method but Collections.Queue has?
Asked Answered
B

1

6

System.Collections.Queue class has Queue.Synchronized method which returns a thread-safe Queue implementation.

But the generic one, System.Collections.Generic.Queue does not have a Synchronized method. At this point I have two questions in mind:

  1. Why doesn't generic one have this method? Is it a framework API design decision?
  2. How is the queue returned from Queue.Synchronized is different than ConcurrentQueue<T> class?

Thanks.

Berchtesgaden answered 3/1, 2013 at 23:23 Comment(0)
I
13

The Synchronized() method returns a wrapper queue that slaps a lock around every method.
This pattern is not actually useful when writing multi-threaded applications.

Most real-world use patterns will not benefit for a synchronized collections; they will still need locks around higher-level operations.

Therefore, the Synchronized() methods in System.Collections are actually a trap that lead people into writing non-thread-safe code.


The ConcurrentQueue<T> class is specifically designed for concurrent applications and contains useful methods that atomically modify the queue.

The concurrent collections package only contain methods that make sense to use in a multi-threaded environment (eg, TryDequeue()); they will help guide you to write code that is actually thread-safe.

This is called the pit of success.

For much more information, see my blog

Inobservance answered 3/1, 2013 at 23:27 Comment(1)
I'd really appreciate if you can answer to my first question above. Thanks!Berchtesgaden

© 2022 - 2024 — McMap. All rights reserved.