473,224 Members | 1,345 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,224 software developers and data experts.

What is the difference between SyncRoot and Synchronized method in Queue?


I often use Queue.Synchronized method to create a queue for multithread writing. I also know I could use SyncRoot and lock to write Queue. Could anyone here please explain to me the pros and cons between those two approaches
Thanks a lo

Nov 15 '05 #1
4 10823
The Synchronized wrapper gives you the *illusion* that your code is thread
safe. As soon as you start writing code like:

for (int i = 0; i < collection.Count; i++)

you take chances because another thread may modify the collection (delete an
element for example) between the time you evaluate the Count property and
the time you call the indexer (so you may get an ArrayOutOfBoundException).

With SyncRoot, you use a different pattern, you synchronize in the "caller"
rather than in the "callee". This is more work because you have to worry
about synchronization in all the places where you use the collection. But on
the other hand, this forces you into putting more thought into your
synchronization strategy, and if you do it right, you will write correct

For example, if you don't use the Synchronized wrapper, you have to write
the for loop above as:

lock (collection.SyncRoot)
for (int i = 0; i < collection.Count; i++)

This loop is safe (of course, I assume that you also have locks around every
piece of code that accesses the collection).

The SyncRoot strategy is usually more efficient too, because you don't
synchronize every call to the collection, you synchronize around blocks that
may perform several calls (the original Java collection API -- JDK 1.1 --
was terrible here because the collections were always completely
synchronized, even when you used them in single-thread scenarios).

Of course, your (high level) APIs should not expose the collections. The
collections should always be private stuff that your class uses to do its
own bookkeeping. If your APIs expose unsynchronized collections, you force
every piece of code that uses your class to do its own synchronization, and
you are in for big trouble (perf problems, race condition problems,

So, my recommendation it to use SyncRoot and "external" locking rather than
the Synchronized wrapper, and to encapsulate the locking logic in classes
that don't expose their internal collections directly.

"chrisben" <an*******@discussions.microsoft.com> a écrit dans le message de
news:7B**********************************@microsof t.com...

I often use Queue.Synchronized method to create a queue for multithread writing. I also know I could use SyncRoot and lock to write Queue. Could
anyone here please explain to me the pros and cons between those two
approaches? Thanks a lot


Nov 15 '05 #2
> I think I do get the answers I was looking for. In fact, I have thought
even SyncRoot is not thread safe for interator.

It's safe as long as all threads are locking on SyncRoot (which is really
pointing to "this" of the collection instance). So if your iterating, you
don't want another thread to be removing items at the same time - and they
can't if the other thread syncs on same lock.

The sync wrapper, truely is just a simple wrapper that itself syncs on the
SyncRoot of the Queue instance. Something very close to this:

private class SynchronizedQueue
private Queue q;
private object syncRoot;

internal SynchronizedQueue(Queue q)
this.q = q;
this.syncRoot = q.SyncRoot;

public override object Dequeue()
obj = q.Dequeue();
return obj;

Your effectively doing this when locking on the SyncRoot before your Gets
and Puts. Your locking the same var twice when using both SyncRoot and the
wrapper. If you can gaurentee yourself all methods will lock on SyncRoot,
then the wrapper is not needed and pretty much redundant and a bit slower
because of the twice-locked deal. hth

William Stacey, MVP

Nov 15 '05 #3

Just one additional note:

The Synchronized wrapper may be interesting with very simple collections
like queues and stacks. If all you do with the collection is a set of
Enqueue/Dequeue or Push/Pop that only need individual synchronization, the
wrapper will be more practical, but a soon as you start doing more complex
things with collections (like iterating on their contents), you should use
SyncRoot synchronization.


"chrisben" <an*******@discussions.microsoft.com> a écrit dans le message de
news:35**********************************@microsof t.com...
Thanks Bruno,

I think I do get the answers I was looking for. In fact, I have thought even SyncRoot is not thread safe for interator. Thanks


Nov 15 '05 #4
Thanks for your advices.
Nov 15 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

by: Rich Sienkiewicz | last post by:
Some classes, like Queue and SortedList, have a Synchronized method which gives a thread safe wrapper object for these classes. But the lock() statement does the same thing. Is there any rules as to...
by: Frank Rizzo | last post by:
Some of the classes in the framework are marked as thread-safe in the documentation. In particular the docs say the following: "Any public static (*Shared* in Visual Basic) members of this type...
by: rmunson8 | last post by:
I have a derived class from the Queue base class. I need it to be thread-safe, so I am using the Synchronized method (among other things out of scope of this issue). The code below compiles, but...
by: nhmark64 | last post by:
Hi, Does System.Collections.Generic.Queue not have a Synchronized method because it is already in effect synchronized, or is the Synchronized functionality missing from...
by: Alan Wang | last post by:
Hi there, How can I create synchronized method in vb.net like synchronized method in Java? Thanks in advanced Alan
by: cj | last post by:
members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe. I'm under the impression before you can use a class you have to make an...
by: TS | last post by:
ArrayList myCollection = new ArrayList(); foreach ( Object item in myCollection ) { // code here. } Can someone explain how more than one thread would execute code? So if i have some code in a...
by: darren | last post by:
Hi I have to write a multi-threaded program. I decided to take an OO approach to it. I had the idea to wrap up all of the thread functions in a mix-in class called Threadable. Then when an...
by: =?ISO-8859-1?Q?Nordl=F6w?= | last post by:
I am currently designing a synchronized queue used to communicate between threads. Is the code given below a good solution? Am I using mutex lock/unlock more than needed? Are there any resources...
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
by: veera ravala | last post by:
ServiceNow is a powerful cloud-based platform that offers a wide range of services to help organizations manage their workflows, operations, and IT services more efficiently. At its core, ServiceNow...
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
by: jimatqsi | last post by:
The boss wants the word "CONFIDENTIAL" overlaying certain reports. He wants it large, slanted across the page, on every page, very light gray, outlined letters, not block letters. I thought Word Art...
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.