Threads and Sockets in Java
1. Threads
a. What is a thread?
A thread is a program unit executed independently of other parts of the program. It allows a program to run two or more tasks simultaneously.
b. Provide an example of when using threads would be appropriate.
In a web environment, using threads is appropriate when handling images, text, and animations concurrently.
c. Explain the purpose of the run()
and start()
methods in a thread.
run()
method: Defines the code that the thread will execute.
start()
method: Initiates the execution of a thread.
d. What is the role of a thread scheduler?
The thread scheduler determines the execution order of threads. It selects the thread with the highest priority to run next.
e. Differentiate between the cooperative and preemptive models used in thread execution.
Cooperative Threading:
- A thread retains control of the CPU until it explicitly decides to release it.
- Programmers are responsible for ensuring threads cooperate and share CPU usage.
- Less stable as poor programming can lead to threads not cooperating effectively.
Preemptive Threading:
- The hardware (CPU) can interrupt a running thread, returning control to the operating system.
- The interrupted thread will resume execution from where it left off when it regains CPU time.
f. Why is thread synchronization important?
Thread synchronization is crucial to control thread behavior and prevent conflicts when multiple threads access the same object. It ensures data consistency and reliability.
g. Describe a situation where thread synchronization is applicable.
Consider a bank account with a balance of $200. Two individuals, Person A and Person B, access the same account concurrently from different locations. Person A withdraws $100, while Person B deposits $100. Without thread synchronization, Person A might see a balance of $100 at the end of their transaction, while Person B sees $300. In reality, the account balance should remain $200. Thread synchronization prevents such inconsistencies.
h. Explain the purpose of wait()
, notify()
, and notifyAll()
methods.
wait()
: When called within a synchronized method, it causes the current thread to wait and release the object lock, allowing other threads to acquire it.
notify()
: Randomly selects one thread that is waiting on the object and unlocks it.
notifyAll()
: Notifies all threads waiting on the object, allowing them to compete for the lock. This method is used when a change in the object’s state might benefit multiple waiting threads.
i. What happens when a sleeping thread is interrupted?
An InterruptedException
is thrown. This exception must be caught in the run()
method, and the thread should be terminated gracefully.
2. Socket-Based Communication
In socket-based applications, two types of communication exist:
- Datagram Sockets:
- Uncontrolled message flow, potentially leading to packet loss.
- Connectionless service.
- Uses UDP (User Datagram Protocol).
- Stream Sockets:
- Controlled message flow, allowing for error correction.
- Connection-oriented service.
- Uses TCP (Transmission Control Protocol).
3. Socket Server and Client Implementations
Identify the instructions for Socket Server and Socket Client:
Code | Server | Client |
---|---|---|
Socket s = new Socket(hostname, numDaPorta); | X | |
InputStream in = s.getInputStream(); | X | X |
OutputStream out = s.getOutputStream(); | X | X |
s.close(); | X | X |
ServerSocket server = new ServerSocket(8888); | X | |
Socket s = server.accept(); | X |
4. Explanation of Code Snippets
a) Socket s = new Socket(hostname, numDaPorta);
Creates a new socket connection to the specified hostname
on the given numDaPorta
(port number).
b) InputStream in = s.getInputStream();
Obtains the input stream associated with the socket s
, allowing the program to read data from the socket.
c) OutputStream out = s.getOutputStream();
Retrieves the output stream connected to the socket s
, enabling the program to write data to the socket.
d) s.close();
Closes the socket connection s
, terminating the communication.
e) ServerSocket server = new ServerSocket(8888);
Creates a new server socket that listens for incoming connections on port 8888
.
f) Socket s = server.accept();
Waits for a client connection request and accepts it, establishing a new socket connection s
with the client.
5. Scenario: Ticket Booking System
Scenario Description
A ticket booking system where clients can request information about available seats, ticket prices, and flight details from a central server.
Components
- Client: Sends requests to the server for ticket information.
- Server:
- Listens for client requests using a
ServerSocket
. - Employs threads to handle multiple client requests concurrently.
- Connects to a database to retrieve and update ticket information.
- Listens for client requests using a
- Database: Stores ticket availability, pricing, and flight details.
Illustrative Diagram
+-------+ +-------+ +---------+ | Client | <----->| Server | <----->| Database| +-------+ +-------+ +---------+ Socket Connection
Flow of Events
- The client establishes a socket connection with the server.
- The server accepts the client connection and creates a new thread to handle the client request.
- The client sends a request for ticket information (e.g., available seats, price) to the server.
- The server thread receives the request and queries the database for the requested information.
- The database returns the relevant data to the server thread.
- The server thread sends the ticket information back to the client.
- The client receives and displays the ticket information to the user.