Skip to main content

[Code refactoring] ThreadStatic and NULL checks


ThreadStatic is used when you have content that needs to be static per thread. For example we can have a field that needs to be static per thread and not per application. In the example below we can see that _message field is decorated with ThreadStatic attribute. Each thread will have a different instance of this field.
public class Foo
{
  [ThreadStatic] 
  private static string _messageBuffer;
}
Great, until now we are good. But scrolling some lines below we find the following code:
public class Foo
{
  [ThreadStatic] 
  private static string _messageBuffer;
  
  public void DoSomeAction(string input)
  {
    if ( _messageBuffer == null )
    {
      _messageBuffer = string.Empty;
    }
    _messageBuffer += input;
  }
  
  public void DoMoreAction(string input)
  {
    if ( _messageBuffer == null )
    {
      _messageBuffer = string.Empty;
    }
    _messageBuffer += " " + input;
  }
...
}
This is not good. Why would you like to check at each call if the field is initialized or not. We refactor this as follow:
public class Foo
{
  [ThreadStatic] 
  private static string _messageBuffer = string.Empty;  
  
  public void DoSomeAction(string input)
  {
    _messageBuffer += input;
  }
  
  public void DoMoreAction(string input)
  {
    _messageBuffer += " " + input;
  }
}
Or we could add a static constructor. But surprise (!!!), when our methods are called we get NullReferenceException on our thread static filed. Surprised? Well, we check the code and we see that we initialize the field. But, the initialization is called only on one thread. Because of this, on the rest of the threads the field is not initialized.
Now we understood why the check of null was made on each method. We know the cause, but the old solution was not so good at all.
A solution for our problem would be to create a wrapper property over our field. We need only the getter that can check if the field is initialize or not. In this way the null check will exist only in one location.
public class Foo
{
  [ThreadStatic] 
  private static string _messageBuffer;
  
  private static string MessageBuffer
  {
    get
    {
      if ( _messageBuffer == null )
      {
        _messageBuffer = string.Empty;
      }
      
      return _messageBuffer;
    }
  }
  
  public void DoSomeAction(string input)
  {    
    MessageBuffer += input;
  }
  
  public void DoMoreAction(string input)
  {
    MessageBuffer += " " + input;
  }
}
We don't need a lock when we initialize the field because is unique per thread. This means that two different threads will have two different instance of this object.
If we have more fields that are thread static, we can add a Boolean that check if the thread static fields were initialized. In this way all the fields would be initialize from one shot.
public class Foo
{
  [ThreadStatic] 
  private static string _messageBuffer;
  [ThreadStatic] 
  private static int _messageCount;   
  [ThreadStatic] 
  private static StatusState _currentState;  
  [ThreadStatic] 
  private static bool _isInitialized = false;
  
  private static InitializePerThreadContent()
  {
    _messageBuffer = string.Empty;
    _messageCount = 1;
    _currentState = StatusState.Empty;
    _isInitialized = true;
  }
  
  private static string MessageBuffer
  {
    get
    {
      if ( !_isInitialized )
      {
        InitializePerThreadContent();
      }
      
      return _messageBuffer;
    }
  }
  
  private static string MessageCount
  {
    get
    {
      if ( !_isInitialized )
      {
        InitializePerThreadContent();
      }
      
      return _messageCount;
    }
  }
  
    private static string CurrentState
  {
    get
    {
      if ( !_isInitialized )
      {
        InitializePerThreadContent();
      }
      
      return _currentState;
    }
  }
  
  ...
}

Comments

  1. An alternative for your solution would be the use of the System.Threading.ThreadLocal class, present inside .NET framework since version 4.0.

    ReplyDelete

Post a Comment

Popular posts from this blog

How to audit an Azure Cosmos DB

In this post, we will talk about how we can audit an Azure Cosmos DB database. Before jumping into the problem let us define the business requirement: As an Administrator I want to be able to audit all changes that were done to specific collection inside my Azure Cosmos DB. The requirement is simple, but can be a little tricky to implement fully. First of all when you are using Azure Cosmos DB or any other storage solution there are 99% odds that you’ll have more than one system that writes data to it. This means that you have or not have control on the systems that are doing any create/update/delete operations. Solution 1: Diagnostic Logs Cosmos DB allows us activate diagnostics logs and stream the output a storage account for achieving to other systems like Event Hub or Log Analytics. This would allow us to have information related to who, when, what, response code and how the access operation to our Cosmos DB was done. Beside this there is a field that specifies what was th...

Cloud Myths: Cloud is Cheaper (Pill 1 of 5 / Cloud Pills)

Cloud Myths: Cloud is Cheaper (Pill 1 of 5 / Cloud Pills) The idea that moving to the cloud reduces the costs is a common misconception. The cloud infrastructure provides flexibility, scalability, and better CAPEX, but it does not guarantee lower costs without proper optimisation and management of the cloud services and infrastructure. Idle and unused resources, overprovisioning, oversize databases, and unnecessary data transfer can increase running costs. The regional pricing mode, multi-cloud complexity, and cost variety add extra complexity to the cost function. Cloud adoption without a cost governance strategy can result in unexpected expenses. Improper usage, combined with a pay-as-you-go model, can result in a nightmare for business stakeholders who cannot track and manage the monthly costs. Cloud-native services such as AI services, managed databases, and analytics platforms are powerful, provide out-of-the-shelve capabilities, and increase business agility and innovation. H...

Cloud Myths: Migrating to the cloud is quick and easy (Pill 2 of 5 / Cloud Pills)

The idea that migration to the cloud is simple, straightforward and rapid is a wrong assumption. It’s a common misconception of business stakeholders that generates delays, budget overruns and technical dept. A migration requires laborious planning, technical expertise and a rigorous process.  Migrations, especially cloud migrations, are not one-size-fits-all journeys. One of the most critical steps is under evaluation, under budget and under consideration. The evaluation phase, where existing infrastructure, applications, database, network and the end-to-end estate are evaluated and mapped to a cloud strategy, is crucial to ensure the success of cloud migration. Additional factors such as security, compliance, and system dependencies increase the complexity of cloud migration.  A misconception regarding lift-and-shits is that they are fast and cheap. Moving applications to the cloud without changes does not provide the capability to optimise costs and performance, leading to ...