0% found this document useful (0 votes)
23 views4 pages

Thread-Safe Ticket Booking System

The document outlines a project for developing a thread-safe ticket booking system for a theater managed by John, aimed at processing multiple booking requests concurrently. It includes a Java implementation demonstrating synchronization to ensure accurate seat availability and prevent overbooking. The system allows users to book tickets and displays the final number of available seats after processing all requests.

Uploaded by

Only Menes
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views4 pages

Thread-Safe Ticket Booking System

The document outlines a project for developing a thread-safe ticket booking system for a theater managed by John, aimed at processing multiple booking requests concurrently. It includes a Java implementation demonstrating synchronization to ensure accurate seat availability and prevent overbooking. The system allows users to book tickets and displays the final number of available seats after processing all requests.

Uploaded by

Only Menes
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

Experiment 3.1
Student Name: Aman Kumar UID: 23BCS12527
Branch: BE-CSE Section/Group: 608-B
Semester: 4th Date: 18/03/2025
Subject Name: OOPs using Java Subject Code: 23CSP-202

1. Aim:
John manages a theater with a limited number of seats, and he needs help building a
ticket booking system. You need to implement a system that processes booking
requests concurrently and checks seat availability. The system should allow the
booking of tickets and then display the final available seats after all requests are
processed.

Help John by implementing a system that ensures synchronization between booking


and checking processes.

2. Objective:
The objective of this project is to develop a thread-safe ticket booking system for a
theater managed by John. The system should process multiple ticket booking requests
concurrently, ensuring that seat availability is accurately checked and updated
without conflicts or overbooking. It aims to demonstrate synchronization in
multithreaded environments, maintaining data integrity during simultaneous access.
3. Java Code:

class Theater {
private int availableSeats;

public Theater(int totalSeats) {


[Link] = totalSeats;
}

// Synchronized method to ensure thread safety


public synchronized boolean bookTicket(String customerName, int numberOfSeats) {
if (numberOfSeats <= availableSeats) {
[Link](customerName + " successfully booked " +
numberOfSeats + " seat(s).");
availableSeats -= numberOfSeats;
return true;
} else {
[Link](customerName + " failed to book " + numberOfSeats + "
seat(s). Not enough seats available.");
return false;
}
}

public int getAvailableSeats() {


return availableSeats;
}
}

// Booking task as a Runnable


class BookingRequest implements Runnable {
private Theater theater;
private String customerName;
private int seatsRequested;

public BookingRequest(Theater theater, String customerName, int seatsRequested)


{
[Link] = theater;
[Link] = customerName;
[Link] = seatsRequested;
}

@Override
public void run() {
[Link](customerName, seatsRequested);
}
}

public class TicketBookingSystem {


public static void main(String[] args) {
Theater theater = new Theater(10); // Let's say 10 seats are available

// Create booking threads


Thread t1 = new Thread(new BookingRequest(theater, "Alice", 4));
Thread t2 = new Thread(new BookingRequest(theater, "Bob", 3));
Thread t3 = new Thread(new BookingRequest(theater, "Charlie", 5));
Thread t4 = new Thread(new BookingRequest(theater, "Diana", 2));

// Start all threads (concurrent requests)


[Link]();
[Link]();
[Link]();
[Link]();

// Wait for all threads to finish


try {
[Link]();
[Link]();
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]();
}

// Final seats available


[Link]("\nFinal available seats: " +
[Link]());
}
}
4. Output:

Common questions

Powered by AI

The synchronized keyword in Java is vital in a concurrent booking system as it ensures that the bookTicket method can only be executed by one thread at a time. This prevents race conditions where multiple threads might simultaneously attempt to update the shared resource—available seats—leading to incorrect results like double booking or incorrect seat counts. By synchronizing the method, the system enforces mutual exclusion, guaranteeing that once a thread enters the synchronized method, no other thread can enter any synchronized method on the same object until the first thread exits. This control mechanism safeguards the data integrity and consistency of seat bookings in the multi-threaded environment .

The Java program effectively demonstrates OOP principles such as encapsulation, abstraction, and modularity within a multithreaded context. Encapsulation is shown by the Theater class, which manages its state (availableSeats) through methods, restricting direct access. The use of classes and interfaces abstracts the operations, separating the logic of booking management from the execution mechanism. Modularity is achieved by separating concerns: the booking logic is encapsulated within the Theater class, while the BookingRequest class encapsulates the execution details for each booking operation. Multithreading is integrated seamlessly using Runnable and Thread, illustrating polymorphism where different threads perform diverse booking operations concurrently. This alignment with OOP principles ensures maintainable and scalable design .

The key components for implementing a thread-safe ticket booking system include a class to represent the theater, synchronized methods, and multithreading through Runnable implementations. The critical component for ensuring synchronization is the synchronized method in the Theater class, which prevents multiple threads from accessing and modifying shared data (availableSeats) concurrently. This method ensures that when one thread is executing the bookTicket method, other threads are blocked from executing it until the first thread completes, thus maintaining data integrity and preventing overbooking. The use of Thread objects to handle multiple booking requests concurrently demonstrates multithreading, while the synchronized keyword ensures that these threads do not interfere with each other by providing mutual exclusion for critical sections of code .

The implementation ensures that all threads have completed their execution by using the join method on each Thread instance (t1, t2, t3, t4) before calculating the final number of available seats. The join method makes the main thread wait for each booking thread to finish execution. This blocking mechanism guarantees that no subsequent operations, such as outputting the final count of available seats, are executed until all concurrent booking operations have completed. This approach prevents premature access to shared resources and ensures that the seat count reflects the final state after all transactions are processed .

If two booking threads attempt to book the same number of available seats simultaneously, the synchronized bookTicket method ensures that only one thread can perform the booking operation at a time. One thread will successfully lock the method, evaluate the seat availability, and decrement the count if applicable. The other thread will have to wait until the first thread completes the operation. If, during this waiting period, the available seats are reduced by the first thread's operation, the second thread's request will fail due to insufficient seats. This allows the system to handle concurrent access correctly, preventing double booking and ensuring accurate availability updates .

The system handles multiple booking requests by creating separate threads for each booking operation, which allows concurrent processing. Each thread is an instantiation of the BookingRequest class that implements Runnable. Within the run method of BookingRequest, it calls the synchronized bookTicket method on the Theater object. This synchronized method is crucial for maintaining data integrity as it ensures that only one booking operation can access and modify the availableSeats attribute at a time. This synchronized access prevents race conditions and ensures that booking operations are atomic, thereby maintaining the correct state of seat availability even with simultaneous requests from different threads .

In this ticket booking system, Java's Thread class and Runnable interface play crucial roles in managing concurrency for booking requests. The Runnable interface is implemented by the BookingRequest class, allowing it to define the run method, which the Thread class uses to execute the booking logic. Each booking request is given its own Thread, which runs concurrently with others. By starting these Threads using the start method, the system can process multiple booking requests at the same time, exemplifying concurrent execution. Once execution is complete, threads use the join method to ensure that the system waits for all operations to finish before proceeding to output the final seat count .

The ticket booking system updates seat availability and communicates the success or failure of booking requests through the bookTicket method of the Theater class. This method is synchronized to ensure exclusive access. When a booking request is made, the method checks if the requested number of seats is less than or equal to the number of available seats. If the check passes, it decreases the availableSeats by the requested number and prints a success message. If insufficient seats are available, it prints a failure message. Both outcomes directly update the state of the system and provide immediate feedback on the transaction attempt .

The program determines the final number of available seats by calling the getAvailableSeats method on the Theater instance after all booking threads have been executed and joined. Once all threads have completed, this method retrieves the current state of the availableSeats variable, reflecting the sum total of all successful booking requests. The main method waits for all threads to finish using the join method, ensuring accurate final data after all concurrent operations are concluded .

If the bookTicket method were not synchronized, several issues could arise, leading to data inconsistency. Without synchronization, multiple threads could simultaneously check and attempt to modify the availableSeats attribute. This race condition could result in overselling seats, where multiple clients believe they have successfully booked the same seats, or in inaccurate seat counts, causing the system to reflect more available seats than there actually are. This lack of atomicity in updates would heavily compromise data integrity and could result in operational flaws such as oversold events or customer dissatisfaction due to incorrect booking statuses .

You might also like