Optimistic Locking by concrete (Java) example

Normally when you look into optimistic locking you also use a library like Hibernate or an other JPA-Implementation with @Version support. Example could read like this: public class Person { private String firstName; private String lastName; private int age; private Color favoriteColor; @Version private Long version; } while obviously there is no point of adding … Read more

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 }

Biased locking in java

Essentially, if your objects are locked only by one thread, the JVM can make an optimization and “bias” that object to that thread in such a way that subsequent atomic operations on the object incurs no synchronization cost. I suppose this is typically geared towards overly conservative code that performs locks on objects without ever … Read more

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