Practice
Vehicle abstraction for a parking system, should Vehicle be an abstract class or an interface if it needs to hold state like licensePlate? Why?Solution
Step 1: Identify state holding needs
licensePlateis shared state, which interfaces cannot hold as fields.Step 2: Evaluate options
Abstract classes can hold state and provide default behavior; interfaces cannot hold instance fields, only constants.Final Answer:
Option D -> Option DQuick Check:
Abstract class holds shared state like licensePlate [check]
parkVehicle() is not synchronized, which exact sequence of Thread 1 and Thread 2 calls causes double-booking of the same spot?Solution
Step 1: Identify race condition
Without synchronization, both threads can read spot availability as true before either marks it occupied.Step 2: Trace exact interleaving
Thread 1: isAvailable() -> true, context switch; Thread 2: isAvailable() -> true; both proceed to park, causing double-booking.Final Answer:
Option A -> Option AQuick Check:
Check-then-act gap without synchronization -> double-booking [check]
WeekendFeeStrategy to calculate extra fees for weekend playback in the current music library design. Which approach requires the minimum change while respecting SOLID principles?Solution
Step 1: Identify SOLID principle involved
Open-Closed Principle (OCP) requires adding new behavior without modifying existing code.Step 2: Evaluate options against OCP
Create a newWeekendFeeStrategyclass implementing the existingFeeStrategyinterface and inject it where needed. adds a new strategy class implementing FeeStrategy, no existing class modified, respecting OCP and Dependency Inversion Principle.Final Answer:
Option B -> Option BQuick Check:
New strategy class -> no existing code change -> OCP respected [check]
placeBid() method checks if the auction is still open before accepting a bid. Without synchronizing placeBid(), which exact thread interleaving causes two threads to accept bids after the auction closes, resulting in inconsistent state?Solution
Step 1: Identify check-then-act race
Without synchronization, Thread 1 reads auction open as true but is preempted before recording the bid.Step 2: Thread 2 reads auction open as true and proceeds to record bid as well, both bypassing the closed state check.
Final Answer:
Option D -> Option DQuick Check:
Unsynchronized check-then-act -> double acceptance after close [check]
parkVehicle() method is NOT synchronized, which exact sequence of Thread 1 and Thread 2 causes double-booking of the same spot?Solution
Step 1: Identify the race condition in check-then-act
Without synchronization, Thread 1 reads spot as available (true) but before it marks it occupied, context switches to Thread 2.Step 2: Thread 2 also reads spot as available and proceeds to park
Both threads proceed to park the vehicle, causing double-booking.Final Answer:
Option C -> Option CQuick Check:
Unsynchronized check-then-act -> both threads see available -> double-booking [check]
