Showing posts from 2013

Named Locks and Lock Striping

Suppose there is a function to which a reference to some arbitrary resource is passed (a file name, for example). The function needs exclusive access to that referenced resource, but should allow concurrent access to other resources. On the one hand, a single lock object would synchronize all calls to the function, which would ruin concurrency. On the other hand, the references are arbitrary, so the number of lock objects required is non-deterministic.

Framework support for named locks is kind of thin. The .NET framework offers named mutexes. For .NET developers this seems like an obvious choice, but since they are system-level they are very tricky to implement properly and can get out of sync very easily.

One more broadly applicable approach I've seen involves locking on the interned string representation of the resource reference. Any two references that are the same will convert to the same interned string instance, so the lock will prevent concurrent access. Meanwhile…