简体   繁体   中英

how to handle multiple simultaneous user requests in an application

I am creating an application in Java in which there is a table in database which stores available access slots.

Basically when a user makes a request, the program should find a record in table which has an open(unused) slot. After the user's data is sent to him, that slot is marked as used and cannot be used anymore.

What I am confused about is, how to handle many simultaneous requests... For eg, if 2 requests come in at the same time, then isnt there a possibility of both of them picking up the same slot(record) from the table? How do I ensure that even though there are many simultaneous requests, each request picks a unique unused slot, and that all requests pick different unused slots.

One thing more, I do have many many slots, but it is important that no single slot be picked up by 2 different requests. However even this may change in future, if the number of requests rises tremendously...So I need a solution that is built to handle a huge number of requests in the manner that i have described.

What you want to do is called Connection pooling (example using tomcat here). The solution for the mentioned problem would be to use the semaphoreing system that a database allows, specifically transactions.

First, you read the table and find the first record that is unused. You propagate the number back to your application. Then you try to open the record exclusively (for writing). You check again if the record is still unused, and if it is, fetch the data for the record. Save the data to the record and release it. If, however, the record is suddenly used when you open it for writing, you need to fall back and look for a new record again and repeat the mechanism.

You put your slot pickup requests in a synchronized queue. This way you will guarantee that slot pickup is FIFO (first in first out). You can use this

What DB are you using? MySQL has SELECT ... FOR UDPATE row locking support.

Try this,

Use ArrayBlockingQueue for thread safe access.... This will make sure that only one thread can access the record at a time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM