33import nl .uu .cs .iss .ga .sim2apl .core .agent .AgentID ;
44import nl .uu .cs .iss .ga .sim2apl .core .deliberation .DeliberationRunnable ;
55
6- import java .util .ArrayList ;
7- import java .util .HashMap ;
8- import java .util .List ;
9- import java .util .Objects ;
6+ import java .util .*;
107import java .util .concurrent .*;
118import java .util .logging .Level ;
129import java .util .logging .Logger ;
@@ -26,6 +23,11 @@ public class MatrixTickExecutor implements TickExecutor {
2623 private int tick = 0 ;
2724 private int stepDuration = -1 ;
2825
26+ /**
27+ * A random object, which can be used to have agent execution occur in deterministic manner
28+ */
29+ private Random random ;
30+
2931 /** The ExecutorService that will be used to execute one sense-reason-act step for all scheduled agents **/
3032 private final ExecutorService executor ;
3133
@@ -48,6 +50,21 @@ public MatrixTickExecutor(int nThreads) {
4850 this .storeThread = new MatrixStoreThread (0 , CONTROLLER_ADDRESS , CONTROLLER_PORT );
4951 }
5052
53+ /**
54+ * Constructor that allows setting a (seeded) random, for ordering deliberation cycles
55+ * before each tick.
56+ *
57+ * <b>NOTICE:</b> when the number of threads is larger then 1, some variation in order of
58+ * agent execution may still occur. If agents use the same random object for selecting actions,
59+ * the nextInt they receive may no longer be deterministic
60+ * @param nThreads Number of threads to use to execute the agent's sense-reason-act cycles.
61+ * @param random A (seeded) random object
62+ */
63+ public MatrixTickExecutor (int nThreads , Random random ) {
64+ this (nThreads );
65+ this .random = random ;
66+ }
67+
5168 /**
5269 * {@inheritDoc}
5370 */
@@ -76,6 +93,11 @@ public HashMap<AgentID, List<String>> doTick() {
7693 runnables = new ArrayList <>(this .scheduledRunnables );
7794 this .scheduledRunnables .clear ();
7895 }
96+
97+ if (this .random != null ) {
98+ runnables .sort (Comparator .comparing (deliberationRunnable -> deliberationRunnable .getAgentID ().getUuID ()));
99+ Collections .shuffle (runnables , this .random );
100+ }
79101
80102 try {
81103 LOG .info ("Sending runnables to agent thread" );
0 commit comments