0

I am developing billing software in java. In my application user opens a window for creating an invoice.

When the window opens it fetchs the MaxID and returns a long MaxID+1 from the INVOICE table and displays it in a Jlabel. Now when user starts billing everytime the invoice number will be MaxID+1. This system runs fine in single user application.

But when this application runs in multiple computer a great issue happens. When Two users, say, userOne and userTwo opens the same window at the same time they will get the same MaxID+1. and as a result Both of them will enter data in the same invoice number. How can I resolve this?

Please help.

Pranjal Choladhara
  • 845
  • 2
  • 14
  • 35

1 Answers1

1

Classical scenario of Race Condition. You need to Synchronize the access to MaxId. Based on your database you need to lock the Invoice table before accessing the MaxId and unlock it once you retrieve it. The retrieval of MaxId must be atomic.

shazin
  • 21,379
  • 3
  • 54
  • 71
  • 2
    Probably best to do that syncronization in a stored proceedure on the DB which does the MaxID+1 update and returns the value, then have your application call that proceedure to get the next ID. That allows for totally separate instances of the application to co-exist. – BruteForce Feb 22 '13 at 12:19