I am developing a hotel booking site. It is a J2EE 1.4 web application and using JSP and JDBC.
I have one method which is responsible to book the hotel rooms.
booking()
And from this method I am calling other four methods
bookRooms()
makePayment()
confirmUserByMail()
confirmUserBySMS()
I am aware that two users can try to book the same room at the same time and in my current system it is possible that two users might end up with the same room.
How should I handle the transaction to avoid this concurrency issue?
It might be very common scenario but I never handled this kind of scenario before, so please guide me.
We can use the setAutoCommit, commit and rollback methods to manage transactions using JDBC. We can use PreparedStatement in transactions to execute the SQL statement, after using PreparedStatement in the statement will execute as per transaction order.
To enable manual- transaction support instead of the auto-commit mode that the JDBC driver uses by default, use the Connection object's setAutoCommit() method. If you pass a boolean false to setAutoCommit( ), you turn off auto-commit. You can pass a boolean true to turn it back on again.
Staring a transaction You can enable manual-transaction support by turning off the auto-commit mode. To do so, you need to passing the boolean value false to the setAutoCommit() method of the Connection interface.
By default, JDBC uses an operation mode called auto-commit. This means that every update to the database is immediately made permanent. Any situation where a logical unit of work requires more than one update to the database cannot be done safely in auto-commit mode.
Easiest way is add locks in your code or use locks provided by database.You can use volatile or other concurrent tools in java.
If the amount of user is not too large,you can use message queue.Visit from user is encapsulated into object, put the object into the queue and wait for process by threads. It's gonna cost a lot of memory space if there are too many users.
I've heard another way called Optimistic lock,but I've never used it in practice,you can try.
ps If the amount of user is very large,perhaps you should use cache like Memcached.Manipulate datas in the memory and map these changes to database later
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With