473,671 Members | 2,420 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Thread safety in Hashtables remove method ..

Hello!

I'm am currently working on making a central cache component threadsafe, and
was looking at the synchronized implementation of the Hashtable. I was
wondering why you'd really want to enforce thread safety in a remove method?

Why would you care if two threads are trying to remove the same key from the
hashtable? In the end, the key is removed (and that was probably what you
were looking for).

Maybe this is caused by me not reading the following code correctly - and
not seing what it actually does is to make sure that no two threads are
removing keys, while other operations are performed on the hashtable (by
other threads).

public override void Remove(object key)
{
object local;

Monitor.Enter(l ocal = _table.get_Sync Root());
try
{
_table.Remove(k ey);
}
finally
{
Monitor.Exit(lo cal);
}
}

--
venlig hilsen / with regards
anders borum
--
Nov 16 '05 #1
4 3340
> Why would you care if two threads are trying to remove the same key from the
hashtable? In the end, the key is removed (and that was probably what you
were looking for).
The problem is that the Hashtable can be grown by adding items while items are
being removed. These growth operations change the way the Hashtable works
such that if the Remove method init's it's search values for finding the key,
and then
the underlying collection changes, you'll get erroneous results.

If the method were to take a local reference of buckets, then even stranger
results
would occur. When the collection was grown, the key would be removed from the
previous collection, and not the grown collection. In effect the item wouldn't
be
removed.
--
Justin Rogers
DigiTec Web Consultants, LLC.
Blog: http://weblogs.asp.net/justin_rogers
Maybe this is caused by me not reading the following code correctly - and
not seing what it actually does is to make sure that no two threads are
removing keys, while other operations are performed on the hashtable (by
other threads).

public override void Remove(object key)
{
object local;

Monitor.Enter(l ocal = _table.get_Sync Root());
try
{
_table.Remove(k ey);
}
finally
{
Monitor.Exit(lo cal);
}
}

--
venlig hilsen / with regards
anders borum
--

Nov 16 '05 #2
Hello!

So the locking process occurs on the entire instance of the instance,
effectively serializing all write (or change operations), so that only on
thread is able to change the instance at any given time?

Naturally all threads are allowed read operations.

Considering the following two methods, I would like to know if the locking
occurs on the instance (_table.get_Syn cRoot()) or on the local object
variable (named "local").

public override void Add(object key, object value)
{
object local;
Monitor.Enter(l ocal = _table.get_Sync Root());
try
{
_table.Add(key, value);
}
finally
{
Monitor.Exit(lo cal);
}
}

public override void Remove(object key)
{
object local;
Monitor.Enter(l ocal = _table.get_Sync Root());
try
{
_table.Remove(k ey);
}
finally
{
Monitor.Exit(lo cal);
}
}

... isn't the above equal to (given that the entire instance is locked):

public override void Remove(object key)
{
object local;
lock(local = _table.get_Sync Root());
{
_table.Remove(k ey);
}
}

or simply this:

public override void Remove(object key)
{
lock(_table.get _SyncRoot());
{
_table.Remove(k ey);
}
}

Thanks in advance. I am really currently reading up on threading and would
like some pointers to emphasize what I get from the books. The more I read,
the more I understand just how important thread safety is to e.g.
collections that serve as caches ..

--
venlig hilsen / with regards
anders borum
--
Nov 16 '05 #3
Anders Borum <a@b.dk> wrote:
So the locking process occurs on the entire instance of the instance,
effectively serializing all write (or change operations), so that only on
thread is able to change the instance at any given time?
Yes.
Naturally all threads are allowed read operations.
That's not necessarily "natural" - if a writing thread temporarily has
the table in an invalid state, reading from it would be a bad idea.
Considering the following two methods, I would like to know if the locking
occurs on the instance (_table.get_Syn cRoot()) or on the local object
variable (named "local").
They're the same thing. The code below is exactly equivalent to

lock (_table.SyncRoo t)
{
...
}

as you suggested (using the property syntax rather than calling the
get_SyncRoot method directly).
Thanks in advance. I am really currently reading up on threading and would
like some pointers to emphasize what I get from the books. The more I read,
the more I understand just how important thread safety is to e.g.
collections that serve as caches ..


See http://www.pobox.com/~skeet/csharp/threads/ for most of what I know
about threading.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #4
Hello!
That's not necessarily "natural" - if a writing thread temporarily has
the table in an invalid state, reading from it would be a bad idea.
Sorry; What I ment was, that from what I have seen in the Hashtable, reading
operations are not synchronized. Again, this is because the implementation
of the Hashtable allows for this. I agree with you that one could easily
think of situations where all operations on a instance are synchronized.
as you suggested (using the property syntax rather than calling the
get_SyncRoot method directly).
The code was taken directly from Salamanders C# decompiler. I am using the
SyncRoot property in my own code. Also thanks for clearing up the
lock(this); code.
See http://www.pobox.com/~skeet/csharp/threads/ for most of what I know
about threading.


I'll read that right away.

--
venlig hilsen / with regards
anders borum
--
Nov 16 '05 #5

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

Similar topics

5
1782
by: Keith Langer | last post by:
I have a hashtable which is accessed by two threads. One thread does all writing and enumeration in the hashtable, and the other thread has read-only access to the table directly through keys but never with enumerators. Is there any reason to worry about synclocks? thanks, Keith
4
6642
by: Jonathan Burd | last post by:
Greetings everyone, Here is a random string generator I wrote for an application and I'm wondering about the thread-safety of this function. I was told using static and global variables cause potential problems for thread-safety. So far, I'm only confused. I need a proper explanation for the concept so I can understand how to write thread-safe functions in the future. My apologies for posting a long routine.
2
1366
by: Frank Rizzo | last post by:
I tried it on dotnet.vb, but got no answers. I'll try it here now. I have an app that listen to data on a certain resource. Data can come in on this resource any time, so I have to listen for it the entire time. I wanted to see if what I have is thread-safe and makes sense. Consider the code below. The app starts and creates code to handle an even from the Listener class. The listener class creates a new thread (will call it thread BOB)...
1
8735
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...
5
15573
by: Cyrus | last post by:
I have a question regarding synchronization across multiple threads for a Hashtable. Currently I have a Threadpool that is creating worker threads based on requests to read/write to a hashtable. One function of the Hashtable is to iterate through its keys, which apparently is inherently not thread-safe. Other functions of the Hashtable include adding/modifying/deleting. To solve the synchronization issues I am doing two things: 1. Lock...
11
2240
by: dee | last post by:
OleDbCommand class like many .NET classes has the following description in its help file: "Thread Safety Any public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Any instance members are not guaranteed to be thread safe." I have 2 questions: 1. I thought dynamic variables are thread-safe since threads have their own
17
5316
by: Rainer Queck | last post by:
Hi NG, one more question about thread safety of generic lists. Let's assume a generic list: List<MyTyp> aList = new List<MyType>(); Would it be a problem if one thread removes elements from the list like MyTyp x = aList; aList.Remove(x);
4
2552
by: Warren Sirota | last post by:
Hi, I've got a method that I want to execute in a multithreaded environment (it's a specialized spider. I want to run a whole bunch of copies at low priority as a service). It works well running as a single application. I was wondering if there is a "Thread-Safety Analysis Wizard"? I'm sure I'm grossly off-base with the following, so I'm prepared to be embarrassed. Please point me in the right direction!
6
3135
by: fniles | last post by:
I am using VB.NET 2003 and a socket control to receive and sending data to clients. As I receive data in 1 thread, I put it into an arraylist, and then I remove the data from arraylist and send it to the client. Before adding data to the arraylist, I check if the depth of the arraylist is longer than iMaxQueueDepth, and if it is, I clear the arraylist. Is it possible that while I am clearing the arraylist, the ThreadMain at the same time...
0
8483
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8926
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
8824
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...
0
8673
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
7444
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6236
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5703
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();...
0
4227
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
1815
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.