0

I am building an online travel portal. I have used a singleton class to store the number of rooms available for a particular hotel. But if data is updated in database, there is no way to reflect it in the app , without restarting the server (since i am using singleton). Is there any way to do so or am I wrong somewhere? What is the best approach in solving such problems? (I am using the singleton in place of a global variable)

rove101
  • 11
  • 2
  • `Singleton for number of rooms in a hotel!!!` Why would you do so? That seems a forced use of pattern than a logical one. – Narendra Pathai Aug 30 '13 at 06:21
  • 2
    http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons?rq=1 read these posts which guide you not to use singletons blindly – Narendra Pathai Aug 30 '13 at 06:21
  • Post some code as well. – Narendra Pathai Aug 30 '13 at 06:22
  • 1
    Re-instantiating a singleton poses whole lot of thread safety issues. Also if you need to re-instantiate a singleton, that is a begging that it should not be a singleton at the first place. – Narendra Pathai Aug 30 '13 at 06:23
  • since i do not want two users to book a room simultaneously, i preferred singleton. i can synchronize the booking process , but it will have lots of performance overhead – rove101 Aug 30 '13 at 06:26
  • 2
    you will still have to synchronize a singleton too. There are much better techniques available like lock stripping. Dont use a same lock for whole hotel. You can keep **one lock per room**. So that no two users will be able to book same room at the same time. – Narendra Pathai Aug 30 '13 at 06:28
  • Serializating at sever and Deserializating at client side(App) can get you a new singleton object. A hacky way and not recommended but you may try because you have your design constraint. – Aniket Thakur Aug 30 '13 at 06:29
  • @AniketThakur Not if it is an `enum singleton` :P – Narendra Pathai Aug 30 '13 at 06:30
  • No its not an enum singleton . Its a double checked locking. Further two users can book the same room if the room count is two. so one lock per room will not do any help – rove101 Aug 30 '13 at 06:34
  • A singleton is not necessary to prevent simultaneous booking of the same room. Synchronization is the best approach for that. Probably using a `synchronized ( hotelRoom ) { ... }` construct at the point of assigning the "winner" of the room. – ash Aug 30 '13 at 06:35
  • To support the multi-booking, put the counter check and update inside the synchronized block. – ash Aug 30 '13 at 06:37
  • In case of two rooms you will hold lock on two rooms simultaneously :) As simple as that. **No of locks held will be same as no of rooms being booked.** Keep in mind to unlock all the locks when booking is cancelled. – Narendra Pathai Aug 30 '13 at 06:51

0 Answers0