vendredi 27 décembre 2019

How to synchronize block in method

I'm building an accounting application and one of the method has been written to save an invoice into the database (MongoDB). Before saving an invoice I must create a number (alphanumeric characters) incrementing the last saved invoice number. Basically, I have to read the last created invoice to get the number and reuse that number + 1 to save the new invoice. To keep the invoice number consistent, I have written the following method:

public synchronized void saveInvoice(InvoiceObject object){
   //Get the last invoice and increment the number
   //Save the InvoiceObject with the incremented number
}

So far so good, but since this application is used by multiple clients, each client has its own invoice numbering sequence so, instead of blocking all clients (threads) while saving an invoice (because of the synchronized), I would like to allow multiple clients accessing the method "concurrently" and queuing the requests of a same client (to keep increasing properly its invoice sequence).

To summarize, here is a diagram of what I want to achieve: Diagram

How can I achieve this?

Thanks :-)

Aucun commentaire:

Enregistrer un commentaire