I have a question about how do we usually deal with threads conflict ? for example, if you are selling a book on a website, and there’s only one available. The situation is that there are 2 clients (threads) want to buy that book and it happens that both place an order at the same time, so how do we deal with it ? and how do we avoid it ?
More specific, I have a servlet that takes request for the client, and I mean since we can’t just make the doPost method synchronized, because that might lead to a performance issue as every request(thread) comes in.
class Server{
private Library library = Library.getInstance(); //singleton for all books
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
synchronized(library){
Book book = library.get(request.getParameter("book_name"));
if(book != null){
int copies = book.getAvailable();
book.setAvailable(copies-1);
placeOrder();
}
}
}
}
The easiest way to deal with problems like that is to use the database to handle concurrency. any mainstream database has concurrency support baked in with years of development effort behind it. it’s relatively easy to leverage the ACID support in the database to handle these kinds of standard business problems.
UPDATE:
As @MartinJames said so well in the comment below, i am not saying that “databases are the solution to all things concurrent”. However, for “longer” lived interactions where you will already be updating a database and you need to control multiple bits of data in a “transactional” nature, the database is the perfect place to handle this level of concurrency.
Additionally, a variety of the other comments are showing how to manage this data in memory using java level concurrency. in this situation, however, the moment you need to “scale out” (i.e. add another app server), you are dead because java level synchronization will no longer work. the database solution, however, still works. this is why EJB stuff discourages using concurrency/synchronization directly. instead, most synchronization in the EJB/JPA world is handled in the database.