C# FAQ: What is the difference between CSharp lock and Java synchronized

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:FAQs
edit

Contents

What is the difference between C# lock and Java synchronized?

Both C# and the Java language support the synchronization of both blocks of code and of methods.

Synchronized code blocks

Both C# and the Java language support synchronized code blocks.

In the Java language, a block of code can be synchronized meaning that only one thread at a time can access a critical section of code of a certain object at a time. For this purpose, the Java keyword synchronized is used.

public void makeWithdrawal (int amount)  // Java example
{ 
 
   synchronized (this)  // only one thread at a time may enter
   { 
      if (amount < this.amount)
      {
         this.amount -= amount;
      }
   }
}

In C#, the lock keyword—semantically identical to the Java synchronized keyword—is used for this purpose.

public void MakeWithdrawal (int amount)  // C# example
{ 
   lock (this)          // only one thread at a time may enter
   { 
      if (amount < this.amount)
      {
         this.amount -= amount; 
      }
   }
}


Synchronized methods

Both C# and the Java language support synchronized methods.

The calling thread locks the object when a synchronized method is called. Therefore, no other threads can call a synchronized method on the same object until the original calling thread releases the object lock—i.e., when the synchronized method exits.

Synchronized methods are marked in Java using the synchronized keyword as shown in the following example:

public class SavingsAccount   // Java example
{
   public synchronized void MakeWithdrawal (int amount)
   { 
      if (amount < this.amount)
      {
         this.amount - amount; 
      }
   }
}

Synchronized methods are marked in C# by annotating the method with the [MethodImpl(MethodImplOptions.Synchronized)] attribute as shown in the following example:

using System;
using System.Runtime.CompilerServices;
 
public class SavingsAccount   // C# example
{
   [MethodImpl(MethodImplOptions.Synchronized)]
   public void MakeWithdrawal (int amount)
   { 
      if (amount < this.amount)
      {
           this.amount - amount; 
      }
   }
}

See also


Personal tools