Madan Madan
Madan Madan

Reputation: 684

PreparedStatement Batch Update in Concurrency Application

I have two methods method A and method B. Method A is responsbile for sending bills to user and Method B is responsbile for updating database. Method B uses PreparedStatement. Method A is run by different concurrent threads at a time. For example

Thread 1- Method A
Thread 2- Method A
Thread 3- Method A

Method A calls Method B to update database for fail or success of the billing.it's like

void A()
{
  send billing sms
 if (successful)
  {
   //update database with successful status
   status='success'
  }

 if unsuccessful{
 status='unsuccess'
  }
  method B(status, connection);

  }

 void B(Status s, Connection con)
  {

   PreparedStatement codes.. for update 

   }

Since, Method A is called by different concurrent threads at a time, How can I implement PreparedStatement Batch function in method B saying I want to update 50 transactions at once and not one by one. I want some counter either created on method A (but since concurrent threads run this method at once, is this possible?) or in method B (but counter variable will again be 0 when called by different concurrent threads, so is this possible?) OR making a Global Counter Class such that each time method B () is called this counter is increased and once it reaches 50 then batch update executes (No idea of it)..

Please advise!!

Upvotes: 2

Views: 389

Answers (2)

Durandal
Durandal

Reputation: 20059

I would not do this at all to be honest.

You should handle the possibility that the update of the DB fails from some reason, which you can't if you batch the updates of totally unrelated billings. Your approach also introduces a good probability that you completely miss a DB update, if the server is shut down while there are pending updates in your batch.

A cleaner approach would be to also process multiple billings in one transaction. Depending on the use case this can be suitable (batch processing) or may as well be completely impractical (if its a user driven action).

Upvotes: 1

user529543
user529543

Reputation:

I would do like this:

Let the method A do whatever he want, but store it to a local buffer the changes, arrayList, Vector, whatever you need. At one some point -at storing changes in java side should be a synchronized block, or a method. At synchronized block you will increment a counter of changer, or check your collection size. If is greater than a predefined value than:

  • block all operations for A, until B is collecting, building data what he need to do.
  • do batch database modification via B
  • empty your collection, reset counter
  • unblock all A methods.

Upvotes: 0

Related Questions