-3

I have some block statements which fetches data from database increment it's value by one and again update in database,If am firing 5 requests it's working fine but if I am firing number of request (consider 10) within few seconds(consider 10 to 15 secs) I am getting same value for 2 to 3 request out of 10 request. what is solution so that I can get next value for each request ? I have tried synchronised block but it's not working...!

Shailesh
  • 657
  • 2
  • 13
  • 27
  • 1
    Well, without seeing your code, the answer cannot be more than a general one: learn about concurrency in Java, good start is [here](http://www.vogella.com/tutorials/JavaConcurrency/article.html), then you can proceed to more detailed [tutorial](https://docs.oracle.com/javase/tutorial/essential/concurrency/). – Jozef Chocholacek Aug 16 '16 at 14:07
  • It sounds more like it should by synchronized in the database. – Jaroslaw Pawlak Aug 16 '16 at 14:09

2 Answers2

0

You could increment the value at the database level where the update will be atomic. e.g.

UPDATE mytable 
  SET logins = logins + 1 
  WHERE id = 12

Then you wont need to synchronize the block in the code.

See this answer for more info on database level increments of values

Community
  • 1
  • 1
Tom Hanley
  • 1,252
  • 11
  • 21
0

Try sequences.

Most database-systems support sequences. The main purpose of a sequence is to give you incremental and unique values.

In a Oracle-database you could query the sql:

CREATE SEQUENCE mysequnece;
SELECT mysequnece.nextval FROM dual;

See What is a sequence (Database)? When would we need it?

Tobias Otto
  • 1,634
  • 13
  • 20