Would you explain lock ordering?

In the simple case given, unlocking in the reverse order is not necessary to avoid a deadlock. However, as the code gets more complicated, unlocking in the reverse order helps you maintain proper lock ordering. Consider: A.lock(); B.lock(); Foo(); A.unlock(); Bar(); B.unlock(); If Bar() attempts to reacquire A, you’ve effectively broken your lock ordering. You’re …

Read more

How to lock several objects?

Well, this question is way too old but, here is a compact one I figured out, both codes will end up to the same compiled statements (this and the one in the question description): lock (obj1) lock (obj2) { // your code }

SemaphoreSlim.WaitAsync before/after try block

According to MSDN, SemaphoreSlim.WaitAsync may throw: ObjectDisposedException – If the semaphore has been disposed ArgumentOutOfRangeException – if you choose the overload which accepts an int and it is a negative number (excluding -1) In both cases, the SemaphoreSlim wont acquire the lock, which makes it unnessacery to release it in a finally block. One thing …

Read more

Asynchronous locking based on a key

As the other answerer noted, the original code is removing the SemaphoreSlim from the ConcurrentDictionary before it releases the semaphore. So, you’ve got too much semaphore churn going on – they’re being removed from the dictionary when they could still be in use (not acquired, but already retrieved from the dictionary). The problem with this …

Read more

java.lang.IllegalMonitorStateException: (m=null) Failed to get monitor for

See the javadoc for Object.wait. in particular “The current thread must own this object’s monitor.” and “[throws] IllegalMonitorStateException – if the current thread is not the owner of the object’s monitor.” That is, you need to synchronize on the object you are going to call wait on. so your code should be: synchronized (available) { …

Read more