From f15f48f499c55b6c8b724d2c3fc67d8082a9bb98 Mon Sep 17 00:00:00 2001 From: marecabo <23156476+marecabo@users.noreply.github.com> Date: Tue, 4 Jun 2024 09:42:17 +0200 Subject: [PATCH] Parallelize DynActivityEngine.doSimStep() --- .../dynagent/run/DynActivityEngine.java | 46 +++++++++++-------- 1 file changed, 26 insertions(+), 20 deletions(-) diff --git a/contribs/dvrp/src/main/java/org/matsim/contrib/dynagent/run/DynActivityEngine.java b/contribs/dvrp/src/main/java/org/matsim/contrib/dynagent/run/DynActivityEngine.java index 729c4e87ff9..cfb0958c0c8 100644 --- a/contribs/dvrp/src/main/java/org/matsim/contrib/dynagent/run/DynActivityEngine.java +++ b/contribs/dvrp/src/main/java/org/matsim/contrib/dynagent/run/DynActivityEngine.java @@ -20,9 +20,9 @@ package org.matsim.contrib.dynagent.run; import java.util.ArrayList; -import java.util.Iterator; import java.util.LinkedList; import java.util.List; +import java.util.Objects; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; @@ -56,25 +56,31 @@ public void doSimStep(double time) { dynAgents.addAll(newDynAgents); newDynAgents.clear(); - Iterator dynAgentIter = dynAgents.iterator(); - while (dynAgentIter.hasNext()) { - DynAgent agent = dynAgentIter.next(); - Preconditions.checkState(agent.getState() == State.ACTIVITY); - agent.doSimStep(time); - // ask agents about the current activity end time; - double currentEndTime = agent.getActivityEndTime(); - - if (currentEndTime == Double.POSITIVE_INFINITY) { // agent says: stop simulating me - unregisterAgentAtActivityLocation(agent); - internalInterface.getMobsim().getAgentCounter().decLiving(); - dynAgentIter.remove(); - } else if (currentEndTime <= time) { // the agent wants to end the activity NOW - unregisterAgentAtActivityLocation(agent); - agent.endActivityAndComputeNextState(time); - internalInterface.arrangeNextAgentState(agent); - dynAgentIter.remove(); - } - } + List agentsToRemove = dynAgents.parallelStream() + .map(agent -> { + + Preconditions.checkState(agent.getState() == State.ACTIVITY); + agent.doSimStep(time); + // ask agents about the current activity end time; + double currentEndTime = agent.getActivityEndTime(); + + if (currentEndTime == Double.POSITIVE_INFINITY) { // agent says: stop simulating me + unregisterAgentAtActivityLocation(agent); + internalInterface.getMobsim().getAgentCounter().decLiving(); + return agent; + } else if (currentEndTime <= time) { // the agent wants to end the activity NOW + unregisterAgentAtActivityLocation(agent); + agent.endActivityAndComputeNextState(time); + internalInterface.arrangeNextAgentState(agent); + return agent; + } + + return null; + }) + .filter(Objects::nonNull) + .toList(); + + dynAgents.removeAll(agentsToRemove); } @Override