Solved

How to ensure concurrency control in servlets?

Posted on 2001-08-24
10
268 Views
Last Modified: 2013-11-24
Hi, may I know how to handle multiple requests to the same servlet that will update the database with the correct implementation of concurrency control?

Let's say we get the number of items in the database table. "Select count(*) from Item" returns 100.

Next we add a new Item using 100 + 1 = 101 as the item_id

Now how can I ensure that the item_id is unique, no two requests starting at the same time has added the item_id, 101 into the database?

Thanks.
0
Comment
Question by:Zuzzi2
10 Comments
 
LVL 7

Expert Comment

by:Igor Bazarny
ID: 6421873
Hi,

I would use stored procedure with proper transaction control/isolation level and let db server handle concurrency issues.

Regards,
Igor Bazarny,
Brainbench MVP for Java 1
www.brainbench.com
0
 
LVL 3

Expert Comment

by:sghosh092199
ID: 6422073
You can also make the particular method as 'synchronized'.

synchronized public int updateCount(int value)
{
value += 1;
return value;

}

When you are doing a SELECT to get the current value, make the SELECT and the UPDATE as an atomic operation.So, the above method can have this variation:

synchronized public void updateCount()
{
//SELECT
item_id += 1;
//INSERT
}
0
 
LVL 3

Expert Comment

by:sghosh092199
ID: 6422110
You can also make the particular method as 'synchronized'.

synchronized public int updateCount(int value)
{
value += 1;
return value;

}

When you are doing a SELECT to get the current value, make the SELECT and the UPDATE as an atomic operation.So, the above method can have this variation:

synchronized public void updateCount()
{
//SELECT
item_id += 1;
//INSERT
}
0
 
LVL 4

Expert Comment

by:sdussinger
ID: 6423326
I would agree with bazarny on using the database for concurrency control. However if this is not possible then a synchronized version much like the one that sghosh suggested would be the correct approach.

Given that, though, there is one slight problem with sghosh's approach.  Since servlets are created and destroyed when connections are accepted, using synchronized in this way will not work. The synchronized keyword as used above will synchronize based on the current instance of an object, but the servlet container will have created multiple instances to support multiple connections. Each of those instances running in their own thread have a monitor which they can use to block access, but since each instance has a different monitor, you can't block access to the database from multiple instances in this way.

What is needed instead is a monitor that all instances of your servlet can share.  For this, we can create a static Object in the servlet class and synchronize on that, instead. The code would look something like:

class DbUpdate
{

  // This is our monitor.
  static Object lock = new Object ();

  .
  .
  .
  public void incrementCounter ()
  {
    synchronized (lock)
    {
      .
      .
      // Do your update here...
      .
      .
    }
  }

}

HTH

--Steve
0
 
LVL 4

Expert Comment

by:sdussinger
ID: 6423334
Actually that DbUpdate class is your servlet. I forgot to add the "extends HttpServlet" to the class definition.

Sorry for any confusion...

--Steve
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 3

Expert Comment

by:sghosh092199
ID: 6423483
> servlets are created
and destroyed when connections are accepted,

> multiple instances to support multiple connections

I think, this is where Servlets are distinguished from CGI.
Servlets are not created in multiple instance to handle multiple connections.

0
 
LVL 4

Expert Comment

by:sdussinger
ID: 6423530
Well, from practical experience, I can safely say that at least one servlet container I've used does create individual instances. I ran into this exact problem several months ago and it turns out that this was the solution.  

While from a specification standpoint, this may not be part of the spec, but there are servlet vendors out there who use multiple instances as a performance improvement, so you can't count on the fact that there will only be one servlet instance...

By using a static lock, you can safely ignore the multiple instance problem, if it exists, and this code will still work when a single instance is all that's being used...


--Steve
0
 
LVL 4

Accepted Solution

by:
sdussinger earned 100 total points
ID: 6423854
After a little more research, I discovered that the servlet specification prior to 2.2 did not specify how multiple instances would be handled. That was left up to the container implementer to decide. In the 2.2 specification, it was tightened to specify that if a Servlet did not implement SingleThreadModel it would only be created once. Any Servlet which does implement SingleThreadModel will be created for each invocation of the servlet.

So servlet containers prior to the 2.2 spec are free to create as many instances as they like, to handle the incoming requests. Servlet containers which are 2.2 compliant should not create multiple instances, unless specifically requested by implementing the SingleThreadModel interface...

--Stevce

0
 
LVL 5

Expert Comment

by:vemul
ID: 7773734
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:

- points to sdussinger

Please leave any comments here within the
next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER !

vemul
Cleanup Volunteer
0
 

Expert Comment

by:SpideyMod
ID: 7861667
per recommendation

SpideyMod
Community Support Moderator @Experts Exchange
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now