Reputation: 335
Lets say I have declared a class like this :
public class PersistableObject<TObject> where TObject : class, new()
{
private readonly object objectLocker = new object();
private TObject persistableObject;
public TObject Object
{
get
{
lock (this.objectLocker)
{
return this.persistableObject;
}
}
set
{
lock (this.objectLocker)
{
this.persistableObject = value;
}
}
}
public bool Persist()
{
lock (this.objectLocker)
{
// Do Persist Object in file
}
}
public bool Retrieve()
{
lock (this.objectLocker)
{
// Do Retrieve Object from file
}
}
}
This class is responsible for storing a variable of any type, persist it to a file and retrieve it from a file.
As you can see, I used the same lock (an object) to lock 4 operations :
Is this the correct approach from concurrency point of view? Am I completely in the safe zone, considering that this class is used by different threads?
UPDATE :
The most important thing for me here, is only one thread should have access to the object at any given time (no matter it wants to get, set, retrieve or persist it). Considering this in mind, is it the correct approach? will any deadlocks or other nasty things happen?
Upvotes: 2
Views: 158
Reputation: 10201
Define "being in the safe zone".
Imagine a piece of code executing on multiple threads using your class to
None of the locking you do here will help making that scenario thread-safe.
Upvotes: 0
Reputation: 171178
Thread-safety is a property of the whole system, not of a single class or method. Individual operations on an instance of this class will execute exclusively, but maybe you require multiple operations to be atomic. The class has no way to do that.
So is it thread-safe or not? Only you can tell because only you know how the class is being used. If operations on this class are truly independent, then it is safe.
If all you had do to obtain thread-safety way to just lock every member of any class, then threading would be a simple task. Threading is complex because it touches everything in a cross-cutting manner.
Upvotes: 4