Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safety object - static or not?

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();
like image 546
Houman Avatar asked Apr 22 '09 22:04

Houman


2 Answers

If a lock object should be static or not depends on the object you want to lock. If you want to lock an instance of a class you cannot use a static lock object. If you want to lock static data you cannot use an instance lock object. So there seems not to be any choice.

You could think about using a static or an instance lock object to lock the access to instance data, but this results in different behaviors. With an instance lock object you lock only an instance while an static lock object will lock all instances. So no choice for performance tuning here, too.

like image 63
Daniel Brückner Avatar answered Oct 19 '22 23:10

Daniel Brückner


He claimed the reason is that static is run at runtime instead of compilation and would make that object slower for threads to lock than if it was non static.

This doesn't really make any sense - I think either the interviewer did not know what he was talking about, or maybe you misunderstood his point.

like image 27
matt b Avatar answered Oct 19 '22 23:10

matt b