madelson / DistributedLock

A .NET library for distributed synchronization
MIT License
1.75k stars 182 forks source link

How are simultaneous requests for the same lock handled? #122

Closed mhsimkin closed 2 years ago

mhsimkin commented 2 years ago

Hi.

I'm reviewing the code to determine if I can build an implementation for MongoDB.

Does the framework, when using any implementation except File and WaitHandles, prevent multiple processes from attempting to acquire the same named lock simultaneously?

If not, how does it recover when that happens?

Thanks.

mhsimkin commented 2 years ago

One other question. Is there a set of examples or an implementation that doesn't use the internal interfaces?

madelson commented 2 years ago

Hi @mhsimkin here are some quick answers to your questions:

Does the framework, when using any implementation except File and WaitHandles, prevent multiple processes from attempting to acquire the same named lock simultaneously?

Exactly! That's the central idea behind distributed locking. As long as the processes trying to acquire the lock can agree on which provider to use (e. g. both using SQL Server with a particular database), only one process (or really one logical thread within that process) can hold a named lock at any given time.

If not, how does it recover when that happens?

Each provider works a bit differently under the hood (some block, some throw exceptions, some return immediately and have to be retried, some register themselves to be notified when the lock becomes available). However, the library abstracts these differences away so that the semantics are the same when you use the different locking classes.

Is there a set of examples or an implementation that doesn't use the internal interfaces?

No. While anyone could implement the public interfaces (e. g. IDistributedLock), the helper methods that support building full-fledged implementations are all marked as internal so that I don't have to maintain backwards compatibility as I evolve them and add new lock types.

The intent of the common code is to factor out common logic between the different DistributedLock.* libraries in this repository, not to provide a foundation for a 3rd party to construct a different distributed lock implementation.

determine if I can build an implementation for MongoDB.

I see you've also filed https://github.com/madelson/DistributedLock/issues/121. Let's keep any mongo-related discussion there.

mhsimkin commented 2 years ago

@madelson Thank you for the response.

If I understand, it is up to each implementation to decide how to handle two requests, from different (servers or process), to lock a resource.