Thursday, February 10, 2011

Synchronizing Methods and Code Blocks

In Java it is possible to specify synchronized blocks of code that ensure that only one thread can access a particular object at a time and then create a critical section of code. C# provides the lock statement which is semantically identical to the synchronized statement in Java.
C# Code

public void WithdrawAmount(int num){

lock(this){

if(num < this.amount)
this.amount -= num;

}

}

Java Code

public void withdrawAmount(int num){

synchronized(this){

if(num < this.amount)
this.amount -= num;

}

}
Both C# and Java support the concept of synchronized methods. Whenever a synchronized method is called, the thread that called the method locks the object that contains the method. Thus other threads cannot call a synchronized method on the same object until the object is unlocked by the first thread when it finishes executing the synchronized method. Synchronized methods are marked in Java by using the synchronized keyword while in C# it is done by annotating the method with the [MethodImpl(MethodImplOptions.Synchronized)] attribute. Examples of synchronized methods are shown below

C# Code
using System;
using System.Runtime.CompilerServices;

public class BankAccount{

[MethodImpl(MethodImplOptions.Synchronized)]
public void WithdrawAmount(int num){

if(num < this.amount)
this.amount - num;

}

}//BankAccount

Java Code

public class BankAccount{

public synchronized void withdrawAmount(int num){

if(num < this.amount)
this.amount - num;

}

}//BankAccount

No comments:

Post a Comment