0

I use a static ThreadLocal to cache some heavyweight objects. Consider the following code:

class MatchItemFinder
{
    private static ThreadLocal<PaddedImage> tempImage;
    MatchItemFinder()
    {
        if(tempImage==null) 
            tempImage = new ThreadLocal<PaddedImage>(
            () => new PaddedImage(patchSize, patchSize));
    }
    internal void DoSomething(){
        //Do something with tempImage.Value
    }
}

When DoSomething() is called from multiple Task Parallel Library threads, when each instance is created? I mean obviously threads are reused so is my tempImage created every time a thread is created or every time a thread is reused?

With a design perspective do you think this kind of caching would be a great decision or there are better strategies to cache large objects in a thread safe manner?

I'm using .Net 4.

morteza khosravi
  • 1,599
  • 1
  • 20
  • 36
  • 1
    http://stackoverflow.com/questions/854976/will-values-in-my-threadstatic-variables-still-be-there-when-cycled-via-threadpo – Kevin Gosse Jul 04 '16 at 19:25
  • What is the goal of your cache? Do you really want every thread to have its own copy of your large object? Or are you really looking at sharing a *single* large object with all threads, but in a thread safe manner? If it's the latter, have a look at the [Lazy](https://msdn.microsoft.com/en-us/library/dd642331(v=vs.110).aspx) class. – sstan Jul 04 '16 at 19:30
  • @sstan You are asking the right question. I don't really want to have like 250 instances of large object. The ideal situation is to have as few instances as the number of concurrent threads that at a specific time are actually doing something on tempImages like 8 instances corresponding to 8 hyper threaded cores. Lazy doesn't do the job because it's not about initialization. The large objects are temporary images manipulated by DoSomething() so a single instance won't work here. – morteza khosravi Jul 04 '16 at 20:00

1 Answers1

2

Thread local variables do not cooperate with the TPL or with the thread pool. They are Thread-based. When any TPL library function reuses a thread your thread locals will be reused.

With a design perspective do you think this kind of caching would be a great decision or there are better strategies to cache large objects in a thread safe manner?

If your cache items are immutable there is no need for thread local items. Use a global cache.

usr
  • 168,620
  • 35
  • 240
  • 369