473,396 Members | 1,968 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,396 software developers and data experts.

Is this easy locking of a Hashtable's element too good to be true?

Much to my surprised the code below compiled and ran. I just don't know
enough about threading to know for sure if this is too good to be true.

I'm attempting to isolate the Hashtable lock to "row level", the whys aren't
important at this time. Does this code actually do what I want?

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace ConsoleForTesting
{
class testHashTableElementLock
{
public static Hashtable ht = Hashtable.Synchronized(new
Hashtable());

static void Main(string[] args)
{
ht["row1"] = "hello world";
Console.WriteLine(ht["row1"]);

lock (ht["row1"])
{
ht["row1"] = "hi there";
}

Console.WriteLine(ht["row1"]);

Console.ReadLine();
}
}
}

Mar 29 '07 #1
4 1640
Mark,

You should clarify what you mean by "row level". The statement itself
says that you want to lock operations on a specific row, however your code
says something different. It seems like what you want to do is isolate
operations on a thread that deal with an element in the hash table.

Your code is only off by a little bit. Instead of locking on
ht["row1"], you should lock on ht. The reason for this is that ht["row1"]
will return an object, but it doesn't synchronize access to the hashtable
itself. Since you are trying to change what a key is associated with, you
have to work on this level.

Now, because you have a synchronized version of the hash table, you
don't have to use the lock statement at all. It's built in for you.

If you didn't have the synchronized hash table, then you would have to
do:

static void Main(string[] args)
{
lock (ht)
{
ht["row1"] = "hello world";
}

lock (ht)
{
Console.WriteLine(ht["row1"]);
}

lock (ht)
{
ht["row1"] = "hi there";
}

lock (ht)
{
Console.WriteLine(ht["row1"]);
}

Console.ReadLine();
}

Now, all of those lock blocks could be combined in various ways. That
depends on how you want your operations to be broken up, and if you want
other threads to have access to any blocks of code locked with ht in between
operations.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com
"Mark S." <ma***@yahoo.comwrote in message
news:%2****************@TK2MSFTNGP05.phx.gbl...
Much to my surprised the code below compiled and ran. I just don't know
enough about threading to know for sure if this is too good to be true.

I'm attempting to isolate the Hashtable lock to "row level", the whys
aren't important at this time. Does this code actually do what I want?

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace ConsoleForTesting
{
class testHashTableElementLock
{
public static Hashtable ht = Hashtable.Synchronized(new
Hashtable());

static void Main(string[] args)
{
ht["row1"] = "hello world";
Console.WriteLine(ht["row1"]);

lock (ht["row1"])
{
ht["row1"] = "hi there";
}

Console.WriteLine(ht["row1"]);

Console.ReadLine();
}
}
}

Mar 29 '07 #2
Niccholas,
says something different. It seems like what you want to do is isolate
operations on a thread that deal with an element in the hash table.
Correct.
Your code is only off by a little bit. Instead of locking on
ht["row1"], you should lock on ht. The reason for this is that ht["row1"]
will return an object, but it doesn't synchronize access to the hashtable
itself. Since you are trying to change what a key is associated with, you
have to work on this level.
There's the rub. I need to lock the "row" because the app is under heavy
load by many users and the business logic dictates that each requests knows
what the other did, make a desicion and then save the result back in to the
row.

By locking the entire Hashtable it blocks all the other threads from doing
their business on other keys. This creates a bottoleneck in my app.

I'd like to enable multple threads to work on other "rows" simoutanously.
Making threads wanting the same "row" wait with a lock is not only okay, but
required.

Any ideas?


Mar 29 '07 #3
Mark,

You don't understand, you don't have a choice in the matter. You are
trying to synchronize access to the hashtable. When you are retrieving an
item from the hashtable, or changing the value that a key points to, you
need to make sure that only one thread at a time is accessing the hashtable.

Then, when you get an object from the hashtable, if you need to
synchronize access to that object, then you can lock on that. However, when
you are accessing the internal data to the hashtable (by reading an object
with a key, or setting a new key), synchronization to the hashtable is a
must.

If you are going to use the synchronized version of the hashtable, then
you don't have to use the lock statement (at least when it comes to the
hashtable itself, for things retrieved from the hashtable, you do).
Generally, I would use the lock statement, since you will more than likely
need to lock off blocks of code, and not just single operations.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Mark S." <ma***@yahoo.comwrote in message
news:uq**************@TK2MSFTNGP05.phx.gbl...
Niccholas,
>says something different. It seems like what you want to do is isolate
operations on a thread that deal with an element in the hash table.

Correct.
> Your code is only off by a little bit. Instead of locking on
ht["row1"], you should lock on ht. The reason for this is that
ht["row1"] will return an object, but it doesn't synchronize access to
the hashtable itself. Since you are trying to change what a key is
associated with, you have to work on this level.

There's the rub. I need to lock the "row" because the app is under heavy
load by many users and the business logic dictates that each requests
knows what the other did, make a desicion and then save the result back in
to the row.

By locking the entire Hashtable it blocks all the other threads from doing
their business on other keys. This creates a bottoleneck in my app.

I'd like to enable multple threads to work on other "rows" simoutanously.
Making threads wanting the same "row" wait with a lock is not only okay,
but required.

Any ideas?


Mar 29 '07 #4
Nicholas,

I assume your decision to use lock statement is based upon this description
from msdn:
Synchronized supports multiple writing threads, provided that no threads are
reading the Hashtable. The synchronized wrapper does not provide thread-safe
access in the case of one or more readers and one or more writers.

Enumerating through a collection is intrinsically not a thread safe
procedure. Even when a collection is synchronized, other threads can still
modify the collection, which causes the enumerator to throw an exception. To
guarantee thread safety during enumeration, you can either lock the
collection during the entire enumeration or catch the exceptions resulting
from changes made by other threads.

Reference:
http://msdn2.microsoft.com/en-us/lib...chronized.aspx
I guess it would be silly to use Synchronized to write and Lock to read. I
would say that you are better off not using syncrhozied at all.

Dave
Mar 30 '07 #5

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

Similar topics

6
by: Jules Winfield | last post by:
I'm often in a situation where I have a Hashtable full of objects. I'm then presented with an object and *if* that object exists in the Hashtable, I need to remove it from the table. I therefore...
7
by: davidw | last post by:
I always use NameValueCollection. But I read an article says the only differece between Hashtable and NameValueCollection is that NameValueCollection could accept more than one value with same key?...
33
by: Ken | last post by:
I have a C# Program where multiple threads will operate on a same Hashtable. This Hashtable is synchronized by using Hashtable.Synchronized(myHashtable) method, so no further Lock statements are...
9
by: Oberon | last post by:
My HashTable (Global.Games) is a static collection of objects of type Game. A Game object has 8 fields (exposed as properties). The key to the HashTable is also one of these fields (GameID, of type...
16
by: akantrowitz | last post by:
In csharp, what is the correct locking around reading and writing into a hashtable. Note that the reader is not looping through the keys, simply reading an item out with a specific key: If i...
9
by: master | last post by:
Actually, it is not only the record locking, what I need, and nobody seems to descibe this. Imagine the following scenario. There is a database with, say 10000 records with some unvalidated...
5
by: Chris Mullins | last post by:
I've spent some time recently looking into optimizing some memory usage in our products. Much of this was doing through the use of string Interning. I spent the time and checked numbers in both x86...
2
by: Bruce | last post by:
Hi I am having a problem understanding the exact advantages of using an ArrayList over a Hashtable in any situation. In most areas of an application I am working on, lookup needs to be fast. If I...
1
by: polastine | last post by:
Hi Anthony -- Anthony Jones wrote: OK, figured as much. I'm not forking any threads myself. 2.0, currently. Why? Is there a difference/advantage? I can probably go to 3.x if there's a...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
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
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,...
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,...

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.