Miguel
Miguel

Reputation: 3506

Static Methods and Multi-Threading

Can there be any problems in having a static class with only static methods (no properties, fields or anything else) and having several threads accessing those methods at the same time?

Upvotes: 1

Views: 2279

Answers (4)

Marc Gravell
Marc Gravell

Reputation: 1064114

As long as there is no shared state or external resources, then: no risk whatsoever. You've mentioned "no fields" etc, which is good - so as long as they aren't indirectly talking shared state (perhaps via some common argument that isn't thread-safe in this scenario, or via some other utility methods that it calls, which share state in messy ways), you should be fine.

Upvotes: 5

vc 74
vc 74

Reputation: 38179

Yes, for instance singleton implementations can be static but they have to implement mechanisms such as double checked locking to prevent multithreading issues.

Upvotes: 0

Rich Turner
Rich Turner

Reputation: 11014

Potentially, yes.

Imagine:

class Logger
{
    WriteToLogs(string msg)
    {
        // Write data to file1
        ... 

        // Write data to file2
        ...
    }
}

Now imagine you have multiple threads trying to call WriteToLog() simultaneously. What happens when thread2 gets scheduled before thread1 is done writing to the log files? You could end up with all manner of data corruption in this case.

Static classes and methods do NOT inherently provide any form of thread synchronization, locking, etc. That's for YOU to design and implement.

Upvotes: 0

TomTom
TomTom

Reputation: 62157

Yes, there can. It depends how your methods are written. Now, if there are only static methods, this would theoreitcally mean fully reentrant code without problems.

Upvotes: 0

Related Questions