I have a client application that communicates with a server. In this application the clients can send requests to the server in order to reserve hotel rooms.
The problems is that, if I have one room left, it is possible that two clients get a reservation.
I have no idea how to avoid it, for this reason I have no code implemented to show.
If I had to guess, I would implement like a singleton.
if (availableRooms()>0) {
synchronized(syncObject_) {
if (availableRooms()>0) {
makeReservation()
}
}
}
return instance_;
}
Is that an acceptable solution? Does it work?
This will only work if you only have one server. If you need to ever scale up, requests may come to different servers and synchronized will not work. In this case you probably will use database anyway and you should use db transactions.