/
AgentInternalEventsDispatcher.java
280 lines (250 loc) · 10.4 KB
/
AgentInternalEventsDispatcher.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
/*
* $Id$
*
* SARL is an general-purpose agent programming language.
* More details on http://www.sarl.io
*
* Copyright (C) 2014-2016 the original authors or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.janusproject.kernel.bic.internaleventdispatching;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import javax.inject.Inject;
import com.google.common.collect.Lists;
import org.arakhne.afc.util.MultiCollection;
import org.arakhne.afc.util.OutputParameter;
import io.janusproject.services.executor.ExecutorService;
import io.sarl.eventdispatching.BehaviorGuardEvaluator;
import io.sarl.eventdispatching.BehaviorGuardEvaluatorRegistry;
import io.sarl.lang.core.Event;
/**
* The class in charge of dispatching every single events coming from the outside of this agent (i.e. from a space) or from an
* agent's behavior.
*
* @author $Author: ngaud$
* @author $Author: sgalland$
* @version $FullVersion$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
*
*/
public class AgentInternalEventsDispatcher {
/**
* The registry of all {@code BehaviorGuardEvaluator} classes containing a method to evaluate the guard of a given behavior
* (on clause in SARL behavior). This class has been inspired by the com.google.common.eventbus.SuscriberRegistry class of
* Google Guava library.
*/
private final BehaviorGuardEvaluatorRegistry behaviorGuardEvaluatorRegistry;
/**
* The executor used to execute behavior methods in dedicated thread.
*/
private final ExecutorService executor;
/**
* Instantiates a dispatcher.
*
* @param executor the executor service.
*/
@Inject
public AgentInternalEventsDispatcher(ExecutorService executor) {
this.executor = executor;
this.behaviorGuardEvaluatorRegistry = new BehaviorGuardEvaluatorRegistry();
}
/**
* Registers all {@code PerceptGuardEvaluator} methods on {@code object} to receive events.
*
* @param object object whose {@code PerceptGuardEvaluator} methods should be registered.
*/
public void register(Object object) {
synchronized (this.behaviorGuardEvaluatorRegistry) {
this.behaviorGuardEvaluatorRegistry.register(object);
}
}
/**
* Unregisters all {@code PerceptGuardEvaluator} methods on a registered {@code object}.
*
* @param object object whose {@code PerceptGuardEvaluator} methods should be unregistered.
* @throws IllegalArgumentException if the object was not previously registered.
*/
public void unregister(Object object) {
synchronized (this.behaviorGuardEvaluatorRegistry) {
this.behaviorGuardEvaluatorRegistry.unregister(object);
}
}
/**
* Unregisters all {@code PerceptGuardEvaluator} methods on all registered objects.
*
* @throws IllegalArgumentException if the object was not previously registered.
*/
public void unregisterAll() {
synchronized (this.behaviorGuardEvaluatorRegistry) {
this.behaviorGuardEvaluatorRegistry.unregisterAll();
}
}
/**
* Posts an event to all registered {@code BehaviorGuardEvaluator}, the dispatch of this event will be done synchronously.
* This method will return successfully after the event has been posted to all {@code BehaviorGuardEvaluator}, and regardless
* of any exceptions thrown by {@code BehaviorGuardEvaluator}.
*
* @param event - an event to dispatch synchronously.
*/
public void immediateDispatch(Event event) {
assert event != null;
Collection<BehaviorGuardEvaluator> behaviorGuardEvaluators = null;
synchronized (this.behaviorGuardEvaluatorRegistry) {
behaviorGuardEvaluators = AgentInternalEventsDispatcher.this.behaviorGuardEvaluatorRegistry
.getBehaviorGuardEvaluators(event);
}
if (behaviorGuardEvaluators != null && !behaviorGuardEvaluators.isEmpty()) {
final Collection<Runnable> behaviorsMethodsToExecute;
try {
behaviorsMethodsToExecute = evaluateGuards(event, behaviorGuardEvaluators);
executeBehaviorMethodsInParalellWithSynchroAtTheEnd(behaviorsMethodsToExecute);
} catch (RuntimeException exception) {
throw exception;
} catch (InterruptedException | ExecutionException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
/*
* <p>If no {@code BehaviorGuardEvaluator} have been subscribed for {@code event}'s class, and {@code event} is not already a
* {@link DeadEvent}, it will be wrapped in a DeadEvent and reposted.
*/
// XXX: not in the SARL specifications. Should we fire the DeadEvent?
/*else if (!(event instanceof DeadEvent)) {
// the event had no subscribers and was not itself a DeadEvent
immediateDispatch(new DeadEvent(event));
}*/
}
/**
* Posts an event to all registered {@code BehaviorGuardEvaluator}, the dispatch of this event will be done asynchronously.
* This method will return successfully after the event has been posted to all {@code BehaviorGuardEvaluator}, and regardless
* of any exceptions thrown by {@code BehaviorGuardEvaluator}.
*
* @param event - an event to dispatch asynchronously.
*/
public void asyncDispatch(Event event) {
assert event != null;
this.executor.execute(() -> {
Collection<BehaviorGuardEvaluator> behaviorGuardEvaluators = null;
synchronized (AgentInternalEventsDispatcher.this.behaviorGuardEvaluatorRegistry) {
behaviorGuardEvaluators = AgentInternalEventsDispatcher.this.behaviorGuardEvaluatorRegistry
.getBehaviorGuardEvaluators(event);
}
if (behaviorGuardEvaluators != null && !behaviorGuardEvaluators.isEmpty()) {
final Collection<Runnable> behaviorsMethodsToExecute;
try {
behaviorsMethodsToExecute = evaluateGuards(event, behaviorGuardEvaluators);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
executeAsynchronouslyBehaviorMethods(behaviorsMethodsToExecute);
}
// XXX: Not in the SAR specification, should we fire the DeadEvent?
/*else if (!(event instanceof DeadEvent)) {
// the event had no subscribers and was not itself a DeadEvent
asyncDispatch(new DeadEvent(event));
}*/
});
}
/**
* Evaluate the guard associated to the specified {@code event} and returns the list of behaviors methods that must be
* executed.
*
* @param event - the event triggering behaviors
* @param behaviorGuardEvaluators - the list of class containing a {@code PerceptGuardEvaluator} method
* @return the collection of couple associating a object and its collection of behavior methods that must be executed
* @throws InvocationTargetException - exception when you try to execute a method by reflection and this method doesn't exist.
*/
private static Collection<Runnable> evaluateGuards(final Event event,
final Collection<BehaviorGuardEvaluator> behaviorGuardEvaluators) throws InvocationTargetException {
final MultiCollection<Runnable> behaviorsMethodsToExecute = new MultiCollection<>();
try {
behaviorGuardEvaluators.parallelStream().forEach((evaluator) -> {
try {
final Collection<Runnable> behaviorsMethodsToExecutePerTarget = Lists.newLinkedList();
evaluator.evaluateGuard(event, behaviorsMethodsToExecutePerTarget);
synchronized (behaviorsMethodsToExecute) {
behaviorsMethodsToExecute.addCollection(behaviorsMethodsToExecutePerTarget);
}
} catch (InvocationTargetException exception) {
throw new RuntimeException(exception);
}
});
} catch (RuntimeException exception) {
final Throwable t = exception.getCause();
if (t instanceof InvocationTargetException) {
throw (InvocationTargetException) t;
}
throw exception;
}
return behaviorsMethodsToExecute;
}
/**
* Execute every single Behaviors runnable, a dedicated thread will created by the executor local to this class and be used to
* execute each runnable in parallel, and this method waits until its future has been completed before leaving.
*
* <p>This function may fail if one of the called handlers has failed. Errors are logged by the executor service too.
*
* @param behaviorsMethodsToExecute - the collection of Behaviors runnable that must be executed.
* @throws InterruptedException - something interrupt the waiting of the event handler terminations.
* @throws ExecutionException - when the event handlers cannot be called; or when one of the event handler has failed during
* its run.
*/
private void executeBehaviorMethodsInParalellWithSynchroAtTheEnd(Collection<Runnable> behaviorsMethodsToExecute)
throws InterruptedException, ExecutionException {
final CountDownLatch doneSignal = new CountDownLatch(behaviorsMethodsToExecute.size());
final OutputParameter<Throwable> runException = new OutputParameter<>();
for (final Runnable runnable : behaviorsMethodsToExecute) {
this.executor.execute(() -> {
try {
runnable.run();
} catch (RuntimeException e) {
// Catch exception for notifying the caller
runException.set(e);
// Do the standard behavior too -> logging
throw e;
} catch (Exception e) {
// Catch exception for notifying the caller
runException.set(e);
// Do the standard behavior too -> logging
throw new RuntimeException(e);
} finally {
doneSignal.countDown();
}
});
}
// Wait for all Behaviors runnable to complete before continuing
doneSignal.await();
// Re-throw the run-time exception
if (runException.get() != null) {
throw new ExecutionException(runException.get());
}
}
/**
* Execute every single Behaviors runnable, a dedicated thread will created by the executor local to this class and be used to
* execute each runnable in parallel.
*
* <p>This function never fails. Errors in the event handlers are logged by the executor service.
*
* @param behaviorsMethodsToExecute - the collection of Behaviors runnable that must be executed.
*/
private void executeAsynchronouslyBehaviorMethods(Collection<Runnable> behaviorsMethodsToExecute) {
for (final Runnable runnable : behaviorsMethodsToExecute) {
this.executor.execute(runnable);
}
}
}