Question

Say if I want to create a Web based booking system for a Multiplex with 2 halls each running 4 shows a day. I want to synchronize booking of seats for each show.

  • Person A tries to reserve 2PM show in Hall A
  • Person B tries to reserve 6PM show in Hall A
  • Person C tries to reserve 2PM show in Hall B
  • Person D tries to reserve 2PM show in Hall A
  • Person E tries to reserve 6PM show in Hall B

Of all these, I want only Person D to wait for person A to complete the booking as they are reserving for same hall and same showtime. All others should be able to book concurrently

My Business layer method has hallName, showId as parameter

public int createBooking(String hallName, int showId){

  //check if there are any available seats
  //access DAO layer to create booking

  return bookingId;
}

I cannot synchronize this method as that will make all bookings wait for one another.

I cannot use semaphore because it dont acquire/release lock based on a parameter. I somehow have to pass in a parameter while acquiring/releasing the lock or create a queue for booking based on the show id. I dont want to hardcode the number of locks because the no of Halls and shows may change over time.

Is there a way to do in Java 6? (Framework - Spring 3 / Server - Websphere7)

There may be a simple approach but I am afraid I am not thinking in right direction.

Was it helpful?

Solution 2

Try this

public int createBooking(String hallName, int showId){
    synchronized ((hallName + showId).intern()) {
        //check if there are any available seats
        //access DAO layer to create booking
        return bookingId;
    }
}

OTHER TIPS

You might have a look at Event Sourcing for his kind of stuff in real life. It's a kind of problem which is quite a classical example of this architecture.

I'm not going to explain the full model here, and I will even betray it, in order to be short:

I would create BookingRequested events, with a unique ID (UUID maybe, or database-provided) and a timestamp, and store those in the database (or in a in-memory queue).

Then a query processor would work on them. It could lock on the in-memory object, or you might even decide that only one thread would work on one room, extracting the unprocessed requests for this particular room. If you can't, and have distant systems working on the same data, the solution might be optimistic locking.

when a decision is taken on the booking, it's a new event, which you will store in the database too. It will contain the reference of the original request, and the result.

Microsoft has a free pdf book, "Exploring CQRS and Event Sourcing", with a very complete example with a similar context (a system for booking places at various conferences).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top