Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 520
ahmet alp balkan Avatar asked Jan 03 '13 23:01

ahmet alp balkan


1 Answers

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

like image 151
SLaks Avatar answered Nov 04 '22 00:11

SLaks