Reputation: 1669
We're using a hashtable to store sessions in a web service. I want to test thread safety of adding to this session. I wrote a Console App which generates lots of threads and adds to this session. But I am neither getting an exception nor losing any data. Am I doing anything wrong or isn't this much of operation a threat to hashtable?!
The operations done on this hashtable are fairly simple: Add, Remove, ContainsKey, [] (getting an entry) and sometimes updating the value of an entry - no foreach or loop.
private const int Threads = 10000;
private const int SleepLimit = 10000;
public static void Main(string[] args)
{
try
{
Console.WriteLine("Application Started.");
Thread[] threads = new Thread[Threads];
for (int i = 0; i < threads.Length; i++)
threads[i] = CreateThread();
Console.WriteLine("All Threads Started.");
foreach (Thread t in threads)
t.Join();
Console.WriteLine("All Threads Joined.");
}
catch (Exception ex)
{
Console.WriteLine("Exception occurred: " + ex.Message);
Console.ReadLine();
}
}
private static Thread CreateThread()
{
Thread thread = new Thread(UserFunction);
thread.Start();
return thread;
}
private static void UserFunction()
{
Thread.Sleep(_random.Next(SleepLimit));
SessionManagement.AddSession("Test");
}
public static void AddSession(string session)
{
ulong hash = NextHashValue();
while (_sessionPool.ContainsKey(hash))
{
Console.WriteLine(string.Format("Duplicate Session Key: {0}-PoolSize: {1}",
hash, _sessionPool.Count);
hash = NextHashValue();
}
_sessionPool.Add(hash, session);
if (!_sessionPool.ContainsKey(hash))
Console.WriteLine("Race problem occurred - Session Key: " + hash);
}
Upvotes: 1
Views: 334
Reputation: 7176
I had the same problem.
The only way I know how to test this is by slowly reviewing all the possible thread/lock interaction in the source code or on a piece of paper.
A long time ago I had an app with 8 threads interacting between them, and it crashed about once time a week of constant use. After a few of these crashes I started to suspect a threading issue. So I managed to simplify a lot the locking code, and then I proved on a piece of paper that all the possible thread/lock interactions were safe. The issue disappeared.
Upvotes: 0
Reputation: 54168
I'm not sure why you re going to such trouble to verify that concurrent writes to Hashtable
are going to crash your app.
Even if your test app runs safely for a long time, you should not deploy code that does not protect your Hashtable
from writes that are concurrent with other read or write operations.
10000 threads is a very large number, by the way - I hope your production app does not plan on using this many.
Upvotes: 2