averbraeck / opentrafficsim

Open Source Multi-Level Traffic Simulator
BSD 3-Clause "New" or "Revised" License
28 stars 8 forks source link

Strategies Demo vehicle number bug #106

Closed WJSchakel closed 4 months ago

WJSchakel commented 5 months ago

The following code creates a NoSuchElementException in the for loop when the number of vehicles is reduced. Synchronizing the method may work, as this code may remove a GTU which a previous call then still needs to loop towards.

        while (getNetwork().getGTUs().size() > this.gtuNum)
        {
            int i = StrategiesDemo.this.stream.nextInt(0, getNetwork().getGTUs().size());
            Iterator<Gtu> it = getNetwork().getGTUs().iterator();
            Gtu gtu = it.next();
            for (int j = 0; j < i; j++)
            {
                gtu = it.next();
            }
            gtu.destroy();
            this.queue.clear();
        }
WJSchakel commented 4 months ago

Synchronization was not the issue. The random selection of a GTU number int i is drawn with upper bound inclusive, it was assumed exclusive. The upper bound also needs to be at least 1. Therefore the following code is now used:

            int n = getNetwork().getGTUs().size();
            int i = n <= 1 ? 0 : StrategiesDemo.this.stream.nextInt(0, n - 1);