Question: Java help: Fix race condition. Below are two snippets from my multithreading java assignment (where the problem I believe lies). I am currently experiencing an
Java help: Fix race condition. Below are two snippets from my multithreading java assignment (where the problem I believe lies). I am currently experiencing an ArrayIndexOutOfBoundsException every 5 or so runs. The issue seems to occur in an example run such as below:
"Three buyers check if the lot is empty, and there are two cars, so the answer is null. Then each removes a car from the lot. The third buyer is left without a car, which is represented by the exception." From CarDealership.java: public Car takeCar() { if (isEmpty()) return null; return cars.remove(0); // Remove 1st } From Buy.java: Car car=carDealerShip.takeCar(); if(car!=null){ // Car has been bought System.out.println("Buyer #"+id+" buys a "+car.toString()); System.out.println("This is buy no. "+buysComplete.incrementAndGet()); } else System.out.println("DID NOT BUY"); synchronized (carDealership) { carDealership.notifyAll(); // Wake up the waiting threads. } Fix up these two snippets to prevent this ArrayIndexOutOfBoundsException (race condition) when I run it in my main.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
