473,406 Members | 2,352 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,406 software developers and data experts.

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

Hi

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

Chris
Nov 15 '05 #1
4 10839
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++)
DoSomething(collection[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
code.

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++)
DoSomething(collection[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,
deadlocks).

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.

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

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

Chris

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


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()
{
lock(syncRoot)
{
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
Cheers!

--
William Stacey, MVP

Nov 15 '05 #3
Thanks.

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.

Bruno.

"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

Chris

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

4
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...
1
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...
6
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...
4
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...
7
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
18
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...
7
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...
167
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...
19
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...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.