开发者

How to execute a thread safety method on the server side in Java?

开发者 https://www.devze.com 2023-03-15 14:51 出处:网络
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.

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.开发者_StackOverflow社区 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.


Your code looks like double check idiom.

But your idea is fine as long as there is only one singleton you synchronize on. (In your example it is syncObject_.) You may have more i.e. when you have more servers running for load balancing. Have a singleton for reservation and do the check for free rooms and the reservation itself in one synchronized scope.


In order to avoid allowing two people to reserve the same room, you have to make sure that only one thread can access whatever object provides the rooms. The most readable way to do this would be to synchronize on the object providing the room reservation service so in this case, you could probably do

synchronized(this){
    //...
    makeReservation()
    //...
}

However, as long as there is only one instance of _syncObject available to all the threads and there is no other place in your code that can possibly call makeReservation(), your method would work as well.

Note, if you are using a database, you can simply set your database's isolation level to SERIALIZABLE, do a database transaction for makeReservation(), and the database will take care of all this for you.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号