The before code allows direct booking without any temporary lock, risking double booking. The after code introduces a hold system that locks a resource for a user temporarily, preventing others from booking it until the hold expires or is confirmed.
### Before: No hold system, direct booking
class ReservationSystem:
def __init__(self):
self.booked_resources = set()
def book(self, resource_id):
if resource_id in self.booked_resources:
return False # Already booked
self.booked_resources.add(resource_id)
return True
### After: Reservation with hold system
import time
import threading
class ReservationSystem:
def __init__(self, hold_time_seconds=30):
self.booked_resources = set()
self.holds = {} # resource_id -> (user_id, expiry_time)
self.hold_time = hold_time_seconds
self.lock = threading.Lock()
def place_hold(self, resource_id, user_id):
with self.lock:
now = time.time()
# Clean expired holds
expired = [r for r, (_, exp) in self.holds.items() if exp <= now]
for r in expired:
del self.holds[r]
if resource_id in self.booked_resources or resource_id in self.holds:
return False # Not available
expiry = now + self.hold_time
self.holds[resource_id] = (user_id, expiry)
return True
def confirm_booking(self, resource_id, user_id):
with self.lock:
hold = self.holds.get(resource_id)
if hold and hold[0] == user_id:
del self.holds[resource_id]
self.booked_resources.add(resource_id)
return True
return False
def release_hold(self, resource_id, user_id):
with self.lock:
hold = self.holds.get(resource_id)
if hold and hold[0] == user_id:
del self.holds[resource_id]
return True
return False