Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between manual locking and Synchronized methods

Is there any difference between this:

internal class MyClass {     private readonly object _syncRoot = new Object();      public void DoSomething()      {         lock(_syncRoot)         {             ...         }     }      public void DoSomethingElse()      {         lock(_syncRoot)         {             ...         }     } } 

and this:

internal class MyClass {     [MethodImpl(MethodImplOptions.Synchronized)]     public void DoSomething()      {         ...     }      [MethodImpl(MethodImplOptions.Synchronized)]     public void DoSomethingElse()      {         ...     } } 

The only difference I see is that the first approach locks on some private member whereas the second approach locks on the instance itself (so it should lock everything else in the instance). Is there any general advice which approach to use? I have currently found two classes with similar purpose in our project each written with different approach.

Edit:

Perhaps one more question. Is this:

internal class MyClass {     [MethodImpl(MethodImplOptions.Synchronized)]     public void DoSomething()      {         ...     } } 

exactly same like this:

internal class MyClass {     public void DoSomething()      {         lock(this)          {             ...         }     } } 
like image 828
Ladislav Mrnka Avatar asked May 26 '11 14:05

Ladislav Mrnka


People also ask

What is the difference between synchronized and lock?

Lock framework works like synchronized blocks except locks can be more sophisticated than Java's synchronized blocks. Locks allow more flexible structuring of synchronized code. This new approach was introduced in Java 5 to tackle the below-mentioned problem of synchronization.

What is a synchronized lock?

When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.

What is intrinsic locks and synchronization?

Synchronization is built around an internal entity known as the intrinsic lock or monitor lock (or simply "monitor"). Intrinsic lock plays an important role in both aspects of synchronization: Enforcing exclusive access to an object's state and establishing happens-before relationships that are essential to visibility.


1 Answers

The first method is preferred because you can (and should) make _syncRoot private. This lowers the risk of deadlocking.

The MethodImplOptions.Synchronized is a left-over from an earlier ambitious idea that turned out to be not so good after all.

Regarding the last question: Yes, according to this blog they are functionally equivalent (but not implemented the same way). And all forms of lock(this) are discouraged, again because of deadlock scenarios.

like image 95
Henk Holterman Avatar answered Sep 28 '22 03:09

Henk Holterman