0

I'm developing a Java application for a simple stock market where people can buy and sell shares of a stock. The question I'm thinking is how to deal with buy/sell concurrency and ensure that 2+ concurrent buy orders will not create duplicate shares for different users?

I'm using MySQL to store all the information and buy and sell orders go to a specific table.

When two users issue simultaneous and immediate buy orders for the same stock, how can I assure that they do not get more shares then those available?

The client connects to a server and the server sends the requests to an RMI server. The RMI is connected to MySQL to store data.

2
  • This solely depends upon the design. This is more of a design decision. Share the table design so that a solution can be thought of
    – Habrashat
    Nov 20, 2013 at 21:12
  • @HarshaBhat edited the post. the table design for orders is simple. it contains what he wants to buy and how much. client sends buy order to Server and Server calls RMI to create a buy order. after each buy order the RMI executes matchOrders() which matches existing buy and sell orders.
    – andrepcg
    Nov 20, 2013 at 22:06

2 Answers 2

1

As long as you use a transaction around each trade, then with any plausible database design, the database won't let this happen. If two threads both try to commit changes to the count of offered shares, one will succeed, and the other will fail with an error. The second thread then just needs to retry the trade.

1

If that is the case, the DB is designed to handle this situation. This is one of the ACID properties of any RDBMS system,

The record gets locked when one transaction is updating the value and is unlocked only upon commit or rollback. And the second transactions either waits or returns back with an error.

If you want to handle it, handle the locks in the DB to give a custom message to the user.

Hope this helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.