Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle multiple servlet requests to update DB value

I will be getting multiple Servlet requests form clients to update some entries in a DB. currently I use hibernate with Postgre. What I do is I read the DB for current value and then add one to that value and save on each request. But if two people read the DB on same time and add it it will not count as I want. I got some suggestions to make it "synchronized". But there can be a considerable delay for some users if number of requests get bigger.

Is there an faster way to update a value by +1, without reading and writing it? If the best practice is to use synchronizing then how to make it faster (less waiting time)?

like image 275
dinesh707 Avatar asked Jan 21 '26 11:01

dinesh707


2 Answers

You could try with a LOCK, check this: http://www.postgresql.org/docs/8.1/static/sql-lock.html

For doing everything (faster) in one query, check this: Increment a value in Postgres

like image 169
cgajardo Avatar answered Jan 24 '26 02:01

cgajardo


You can use Spring transaction management (see docs here).

Spring config:

<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="dataSource"/>
</bean>

Annotate your hibernate read and write methods with @Transactional like

@Transactional(value = "txManager" ...
public int incrementValue(){

Then define isolation property according to your needs. Look at TransactionDefinition for different isolation options. For example, TransactionDefinition.ISOLATION_READ_COMMITTED

like image 31
Luis Ramos Avatar answered Jan 24 '26 04:01

Luis Ramos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!