DEV Community

wennan xu
wennan xu

Posted on

Thread safe strategy in Java or .net

Stateless design

Just like in Java, designing classes without shared mutable state is the safest approach.

public class MyProcessor
{
    public string Process(string input)
    {
        return input.ToUpper(); // No shared state
    }
}

Enter fullscreen mode Exit fullscreen mode

ThreadLocal

ThreadLocal is a .NET class that allows you to store data that is local to a specific thread. Each thread accessing a ThreadLocal instance gets its own independent copy of the data.

private static ThreadLocal<Random> random = new ThreadLocal<Random>(() => new Random());

public int GetRandomNumber()
{
    return random.Value.Next();
}

Enter fullscreen mode Exit fullscreen mode

Synchronized blocks

Use lock (or Monitor) to protect shared resources.

private readonly object _lock = new object();
private List<string> _sharedList = new List<string>();

public void AddItems(List<string> items)
{
    lock (_lock)
    {
        _sharedList.AddRange(items);
    }
}

Enter fullscreen mode Exit fullscreen mode

Thread-safe collections

Thread-safe collections are designed to handle concurrent access without requiring manual locking.
Common Thread-Safe Collections in .NET

Collection               Use Case
ConcurrentDictionary    Key-value store with safe concurrent access
ConcurrentQueue         FIFO queue for producer-consumer scenarios
ConcurrentStack         LIFO stack for concurrent access
ConcurrentBag           Unordered collection for fast insert/retrieve
BlockingCollection  Thread-safe wrapper for producer-consumer with blocking and bounding
Enter fullscreen mode Exit fullscreen mode

Partitioning

Similar to Spring Batch partitioning, you can divide work into chunks and assign each to a separate thread or task.

Parallel.ForEach(partitions, partition =>
{
    ProcessPartition(partition);
});

Enter fullscreen mode Exit fullscreen mode

Immutable data

Immutable types are inherently thread-safe. You can use records or readonly structs in C#.

public record Person(string Name, int Age);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)