title: Alternative ways to handle cuncurrency in a cinema bookin system
body: <p>My group and i have made a cinema booking system for a school project where the subject was cuncurrency control. It is made with c# and entity framework in an n-tier arcitecture where the presentationtier consisted of an mvc project. </p>
  
  <p>We chose to use pessimistic locking (IsolationLevel.ReadCommited) during the "select seats for reservation" phase so that the database is locked while someone is checking if seats are available and when the seats are added to the reservation. I am currently looking if for example optimistic concurrency could have been an option an if so how it would work.</p>
  
  <p>Here is a picture of the database diagram:
  <a href="https://i.stack.imgur.com/4ovoP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4ovoP.png" alt="Diagram over database"></a></p>
  
  <p>When you click on a specific show it will automatically create an empty reservation for you and then build the screen(cinema hall) with it seats and information wheather they are available or not.</p>
  
  <p>Here is the method for creating a list of the seats linked to a screen(cinema hall):</p>
  
  <pre><code>public static List&lt;SeatReservationInfo&gt; GetSeatInfoForShow(Guid reservationId)
          {
              using (EntityContext db = new EntityContext())
              {
                  //Retrieve a reservation on its id
                  var reservation = db.Reservations.FirstOrDefault(r =&gt; r.Id == reservationId);
                  //Retrieve the show linked to the reservation
                  var show = db.Shows.First(i =&gt; i.Id == reservation.ShowId);
                  //Used to check if the reservation is expired
                  var expired = DateTime.Now.Subtract(new TimeSpan(0, 0, 15, 0));
                  //Henter sæder ud tilhørende en specifik sal og laver Seat modellen om til en SeatReservationInfo model
                  //Retrieve all seats linked to a specific screen and turn the Seat model into a SeatReservationModel which containt availablity status of the seat
                  return
                      db.Seats.Where(s =&gt; s.ScreenId == show.ScreenId)
                          .OrderBy(s =&gt; s.RowNumber)
                          .ThenBy(s =&gt; s.SeatNumber)
                          .Select(s =&gt; new SeatReservationInfo
                          {
                              Id = s.Id,
                              Type = s.Type,
                              RowNumber = s.RowNumber,
                              SeatNumber = s.SeatNumber,
                              Availability = s.ReservationSeats.Any(a =&gt; a.ReservationId == reservationId)
                                  ? SeatAvailability.ReservedSelf
                                  : s.ReservationSeats.Any(
                                      a =&gt;
                                          a.Reservation.ShowId == reservation.ShowId &amp;&amp;
                                          (a.Reservation.Status == ReservationStatus.Completed ||
                                           (a.Reservation.Status == ReservationStatus.Started &amp;&amp;
                                            DateTime.Compare(a.Reservation.Created, expired) &gt;= 0)))
                                      ? SeatAvailability.Reserved
                                      : SeatAvailability.Available
                          }).ToList();
              }
          }
  </code></pre>
  
  <p>From this method, the screen(Cinema hall) is built with seats as checkboxes where you can select multible seats at once. Your selected seats is then sent with your reservationId via an AJAX call to the TryBookSeats method which will first see if anyone have tried to reserve your seats and if not then reserve them by placing them in the ReservationSeats table.</p>
  
  <p>Here is the TryBookSeats method:</p>
  
  <pre><code>public static bool TryBookSeats(List&lt;Guid&gt; seatIds, Guid reservationId)
          {
              //bool who will become true if seats are available
              bool success;
              //Starts a database connection
              using (var db = new EntityContext())
              //Starts a transaction where the isolationlevel is set to ReadCommitted (pessimistic concurrency)
              using (var scope = db.Database.BeginTransaction(IsolationLevel.ReadCommitted))
              {
                  //Used to check if the reservation is expired
                  var expired = DateTime.Now.Subtract(new TimeSpan(0, 0, 15, 0));
                  //Retrieve a reservation that hasnt expired
                  var reservation = db.Reservations.First(x =&gt; x.Id == reservationId &amp;&amp; DateTime.Compare(x.Created, expired) &gt;= 0);
                  //Checks if the selected seats are available. if so set success to true
                  success = !db.ReservationSeats.Any(
                      i =&gt;
                          i.ReservationId != reservationId &amp;&amp; i.Reservation.ShowId == reservation.ShowId &amp;&amp;
                          seatIds.Contains(i.SeatId) &amp;&amp;
                          (i.Reservation.Status == ReservationStatus.Completed ||
                           (i.Reservation.Status == ReservationStatus.Started &amp;&amp;
                            DateTime.Compare(i.Reservation.Created, expired) &gt;= 0)));
  
                  if (success)
                  {
                      //Remove last selected seats connected to the current reservation
                      db.ReservationSeats.RemoveRange(db.ReservationSeats.Where(i =&gt; i.ReservationId == reservationId));
                      //Add seats to the database
                      foreach (var id in seatIds)
                      {
                          db.ReservationSeats.Add(new ReservationSeat
                          {
                              Id = Guid.NewGuid(),
                              ReservationId = reservationId,
                              SeatId = id
                          });
                      }
                  }
                  db.SaveChanges();
                  scope.Commit();
              }
              return success;
          }
  </code></pre>
  
  <p>As you can sse have we used the isolationLevel ReadCommited which we presume is pessimistic locking and will ensure that no conflicts ocure while adding the seats to ReservationSeats.</p>
  
  <p>And i presume that we wouldt encounter any deadlocks since we only lock one table.</p>
  
  <p>i understand that one way optimistic cuncurrency works is before you commit an update to the database you will check if the database has been altered since you retrieved the record. Could we have chosen to, before adding the seats(and reservationId) to the reservationSeats table do a check to see if they have been reserved for the show.</p>