While my main programming language is c#, i think this applied for all language maybe…

so during i learn c#, we are told how dangerous to use lock, its performance breaker, bla2
due that warn, a lot of programmer become careless when the need of lock is indeed needed…

http://msdn.microsoft.com/en-us/library/c5kehkcz(v=vs.100).aspx
if you read about lock on msdn article, you will get sample on bank account…

so use lock object to make sure, your bank’s account balance never goes less than zero

The correct solution should be on mutable vs immutable object, NOT use lock vs not use lock
so yes design the class as immutable to make sure account balance never less than zero

so when to use lock?
msdn is correct “Best practice is to define a private object to lock on, or a private static object variable to protect data common to all instances.”

but not on that bank account scenario right?
yep

then when???

consider you have private static dictionary variable to cache data
same key on dictionary will throw exception

private static Dictionary<string, Person> cache=new Dictionary<string,Person>();

public void Add(Person person)
{
if(!cache.ContainsKey(person.Name))
{
cache.Add(person.Name, person);
}
}

run such code on multithread and kaboom its throw exception

private static Dictionary<string, Person> cache=new Dictionary<string,Person>();

public void Add(Person person)
{
lock(cache)
{
if(!cache.ContainsKey(person.Name))
{
cache.Add(person.Name, person);
}
}
}

and thats it ! use it right !

 

Advertisements