Hi,
I need some help on the a
Java interview question on currency.
A friend of mine recently interviewed for a Java position and during the interview, he was presented some code for a fictitious car rental system.
He was asked to identify and fix, among other errors, the concurrency issues with the code. He couldn't quite do it at the interview.
Here is my proposed solution to the problem, but I am not sure if this works and will appreciate some advice.
The code skeleton is given below (some details are omitted for brevity):
Given classes:
The method rentCar() is not
thread safe as one thread could see a car is availabe for hire but before the booking finishes,
another thread could see the same car being availabe and booked it before the original thread. Thus the first thread could override the 2nd thread's booking.
He suggested that he could make synchronized both the methods: rentCar() and returnCar(). This would make it thread safe.
The problem then is that the rentCar() method would be called by many requests. Making it serial will hit the server performance hard,
and he knew he would have to make it multi-threaded, but struggled on how to do it.
Here is my solution, the idea is:
1) Use multiple threads in a thread pool to increase performance. Create hiring and releasing tasks as Callable.
2) To avoid the situation where a car may be booked by multiple threads, guard the booking code with a lock so booking on a car
can only be done by one thread.
3) Use a ConcurrencyHashMap to stores a lock for each Car identified by its registration key. Any thread wants to book a car will
have to acquire the lock for the car before a booking can be made. Given the ConcurrentHashMap is thread safe and locks on its segments,
it will enable many requests being run concurrently, thus improve performance.
The code is listed below and I'll appreciate comments on whether it works; how to safely remove the individual locks? Alternative solutions?