473,734 Members | 2,211 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

Hi

I often use Queue.Synchroni zed 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 10868
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.Coun t; i++)
DoSomething(col lection[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 ArrayOutOfBound Exception).

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.Syn cRoot)
{
for (int i = 0; i < collection.Coun t; i++)
DoSomething(col lection[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*******@disc ussions.microso ft.com> a écrit dans le message de
news:7B******** *************** ***********@mic rosoft.com...
Hi,

I often use Queue.Synchroni zed 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 SynchronizedQue ue
{
private Queue q;
private object syncRoot;

internal SynchronizedQue ue(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*******@disc ussions.microso ft.com> a écrit dans le message de
news:35******** *************** ***********@mic rosoft.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
8056
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 when to use one and not the other? For instance, if I wanted to remove an item in a SortedList, would it be better to lock() it or do it via the Synchronized wrapper? Why choose one over the other SortedList sl lock(sl sl.Remove(item) O
1
8740
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 are thread safe. Any instance members are not guaranteed to be thread safe." What exactly does this mean? Does this mean that if I call a shared method from 2 different threads, nothing whacky will happen? Also when it says that instance members...
6
3735
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 at runtime, the cast of "Queue.Synchronized(new EventQueue())" to an EventQueue object is failing stating invalid cast. Why? public class EventQueue : System.Collections.Queue { ... }
4
8190
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 System.Collections.Generic.Queue? Putting it another way can I safely replace a System.Collections.Queue.Synchronized(myUnSynchronizedQueue) with a System.Collections.Generic.Queue while porting a working 2003 project? Thanks,
7
7254
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
1981
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 instance of it. So how can a class be threadsafe by itself but an instance of it not be? I guess I don't get what exactly being threadsafe means. Multiple theads can use the same instance of a class?
7
2873
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 web page that a user runs that iterates over an arraylist, what is the scenario where more than one thread would be running this code and could possibly modify the collection before the iteration of the arraylist completes?
167
8313
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 object should run in its own thread, it should implement this mix-in class. Does this sound like plausible design decision? I'm surprised that C++ doesn't have such functionality, say in its STL. This absence of a thread/object relationship in...
19
3396
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 out there on the Internet on how to design *thread-safe* *efficient* data- structures? /Nordlöw
0
8774
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9447
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9307
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9235
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9181
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6031
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3261
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2721
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2180
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.