Skip to content

Commit

Permalink
clean(mapping): avoid instantiation of selectors using map cache
Browse files Browse the repository at this point in the history
Signed-off-by: Karl Schrab <[email protected]>
  • Loading branch information
kschrab committed Jul 28, 2023
1 parent 77432e3 commit 12e9516
Showing 1 changed file with 16 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@

import org.apache.commons.lang3.ObjectUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nonnull;

/**
Expand All @@ -56,7 +58,8 @@ public class MappingAmbassador extends AbstractFederateAmbassador {
/**
* Read the <code>CMappingAmbassador</code> from the configuration.
*/
private CMappingAmbassador mappingAmbassadorConfiguration;
private final CMappingAmbassador mappingAmbassadorConfiguration;


/**
* Pointer to save the {@link ScenarioTrafficLightRegistration} when it arrives too early.
Expand All @@ -65,6 +68,11 @@ public class MappingAmbassador extends AbstractFederateAmbassador {

private RandomNumberGenerator randomNumberGenerator;

/**
* Cache stochastic selectors to avoid unnecessary instantiations.
*/
private final Map<String, StochasticSelector<CPrototype>> typeDistributionSelectors = new HashMap<>();

/**
* Constructor for the {@link MappingAmbassador}.
*
Expand Down Expand Up @@ -126,7 +134,12 @@ private void handleInteraction(ScenarioVehicleRegistration scenarioVehicle) thro

final List<CPrototype> typeDistribution = framework.getTypeDistributionByName(scenarioVehicle.getVehicleType().getName());
if (!typeDistribution.isEmpty()) {
final CPrototype selected = new StochasticSelector<>(typeDistribution, randomNumberGenerator).nextItem();
StochasticSelector<CPrototype> selector = typeDistributionSelectors.get(scenarioVehicle.getVehicleType().getName());
if (selector == null) {
selector = new StochasticSelector<>(typeDistribution, randomNumberGenerator);
typeDistributionSelectors.put(scenarioVehicle.getVehicleType().getName(), selector);
}
final CPrototype selected = selector.nextItem();
sendVehicleRegistrationForScenarioVehicle(scenarioVehicle, selected.group, selected.applications);
} else {
final CPrototype prototype = framework.getPrototypeByName(scenarioVehicle.getVehicleType().getName());
Expand Down Expand Up @@ -197,6 +210,7 @@ public void initialize(long startTime, long endTime) throws InternalFederateExce
// enriched with functionality)
framework = new SpawningFramework(mappingAmbassadorConfiguration, scenarioTrafficLightRegistration, rti, randomNumberGenerator);

typeDistributionSelectors.clear();
// Send out the VehicleTypesInitialization, publishing information
// about the different vehicle types in the simulation
rti.triggerInteraction(framework.generateVehicleTypesInitialization());
Expand Down

0 comments on commit 12e9516

Please sign in to comment.