AgencyAndId vehicleId = record.getVehicleId();
while (true) {
VehicleLocationCacheEntry newCacheEntry = new VehicleLocationCacheEntry(
blockInstance);
VehicleLocationCacheEntry cacheEntry = _entriesByVehicleId.putIfAbsent(
vehicleId, newCacheEntry);
if (cacheEntry == null) {
cacheEntry = newCacheEntry;
/**
* Since we're adding a new entry, we indicate the connection between
* this block instance and vehicleId
*/
ConcurrentCollectionsLibrary.addToMapValueSet(
_vehicleIdsByBlockInstance, blockInstance, vehicleId);
}
/**
* If the block instance of a vehicle has changed mid-stream, we close off
* the cache entry and remove the block=>vid mapping
*/
if (cacheEntry.isClosedBecauseBlockInstanceChanged(blockInstance)) {
_entriesByVehicleId.remove(vehicleId);
ConcurrentCollectionsLibrary.removeFromMapValueSet(
_vehicleIdsByBlockInstance, cacheEntry.getBlockInstance(),
vehicleId);
continue;
}
/**
* If the element failed to add because the entry is closed, we loop.
* Someone closed the entry while we were in the process of requesting it
* from the map. On the next loop, it should no longer be in the map.
*/
if (!cacheEntry.addElement(record, scheduledBlockLocation, samples))
continue;
BlockInstance existingBlockInstance = cacheEntry.getBlockInstance();
if (!blockInstance.equals(existingBlockInstance))
ConcurrentCollectionsLibrary.removeFromMapValueSet(
_vehicleIdsByBlockInstance, existingBlockInstance, vehicleId);
// Ensure the block => vehicle mapping is set
return cacheEntry.getElements();
}
}