Alex Rivera | Logout

Thread safety object - static or not?

Asked 2009-04-22T22:32:04.553
11

I was recently in an interview and the tech guy asked me about how to make an application thread-safe.

Well, after explaining the lock() correctly, he said it is not a good idea to have the object as static.

private static readonly object _syncLock = new object();

He claimed the reason is that static makes that object slower for threads to lock than if it was non static. Is this true?

EDIT: Nonetheless I am still not sure. What is the difference between these three approaches?

private static readonly object _syncLock = new object();
public static readonly object _syncLock = new object();
private readonly object _syncLock = new object();
Edit
Report

1 Answer

0

Use a non static object for the lock whenever you need to make sure the same instance isn't manipulated by different threads at the same time.

Lets say you have some List classes, with a special Reorder method that accepts some strange arguments. Consider if you need to reorder 100 different lists during some paralel processes. You only care that different threads don't manipulate the same list at the same time, as it might affect your reorder logic. You don't need a static lock, as you don't care when different lists are being manipulated at the same time.

A simple example of a scenario with a static lock, is initialization of some static data, where you want to make sure the load logic is ran only once. Like some Cache or a Singleton.

answered 2009-04-23T09:22:37.080

Your Answer