Xaqron
Xaqron

Reputation: 30857

Choosing right object for locking in thread synchronization?

Generally code samples use locks this way:

static readonly object lockForWorkingWithSharedObject = new object();

lock(lockForWorkingWithSharedObject)
{
   // do something with shared object
}

This way we need many locks in a large class. Is it good practice to use the shared object itself as the synchronization object ?

// of course here sharedObject is a reference type
lock(sharedObject)
{
   // do something with sharedObject
}

Upvotes: 0

Views: 110

Answers (1)

Martin v. Löwis
Martin v. Löwis

Reputation: 127467

In Java and .NET, the point of having each object lockable is precisely because language designers thought it would be useful to use the object itself as the lock; hence also the synchronized keyword in Java.

If you need much finer granularity of locking, I would assume that you better split the state of your object in multiple objects, grouped by things that semantically belong together, and thus likely also need to protected against concurrent access together.

Upvotes: 1

Related Questions