When is Thread Local Storage needed

stephen.anders

New member
Joined
Jul 8, 2010
Messages
3
Location
Atlanta, GA
Programming Experience
5-10
I have a windows service (that I inherited from a previous employee) which on a timer creates an object from a referenced DLL to process reports (output via Excel automation). Since the timer is a threading timer, each iteration starts a new thread to process a separate report. The code in the DLL does lots of db queries and looping to get all the data needed to process the report. All of the data that is used in processing these reports is stored in Thread Local Storage so we dont worry about one reports data stepping on or getting mixed up with another reports data.

The problem is there are some performance issues with all of the type casting in and out of Thread Local Storage (the data for each slot is always stored as Object).

I was thinking that the use of Thread Local Storage here was overkill and not needed b/c the thread is created in the service, once the thread starts it declares and instantiates a local object from the referenced DLL, and ALL of the report processing happens within that local object.

In this scenario, I would think that we would not need to worry about synchronization b/c the object they are trying to synchronize has been declared and instantiated local to each thread. Am I correct in this? Is an object created on one thread (which does not access other threads) always safe from other objects (of the same type) created on a different thread? Does the fact that we are instantiating an Excel object and outputting the report to an Excel worksheet change the answer to this question at all?
 
A member variable is always accessible throughout the object its a member of and a local variable is only accessible within the method it's declared in. The scenario where thread local storage is useful is when you have you have multiple threads executing methods that are members of the same object (not just the same class, but the same instance of that class). If you were to just use member variables then every thread would have access to the same data, possibly causing synchronisation issues.

Now, if each thread is executing methods of a different object, so they don't have access to the same member variables, then there is no benefit to using thread local storage. If threads can't compete for the same data then there's no point taking steps to isolate each thread's data.
 
Back
Top