If we have a number of available product items to sell in a variable quantity. What will happen when quantity = 1 and two users access it at the same time (both want to buy 1 item - that is decrease variable by one)?!
public Boolean Check()As both users access at the same time, condition will be for both true and program will decrease quantity. Resulting in overselling our available stock.
{
if(quantity>buyQuantity)
{
decreaseQuantity(buyQuantity);
}
}
When we use synchronized methods, only one thread at time is possible. Program will carry out request of user one, other user request will wait. After first request is carried out, second request will be handled.
using System.Runtime.CompilerServices;
[MethodImpl(MethodImplOptions.Synchronized)]
public Boolean Check()
{
if(quantity>buyQuantity)
{
decreaseQuantity(buyQuantity);
}
}
Email this
Hits: 2588
Comments (1)

Write comment


