public void execute(Runnable runnable, int timeoutSeconds, int[] latches, EntryEventType eventType, ReplicatedMap... replicatedMaps) throws TimeoutException {
final String[] registrationIds = new String[latches.length];
final WatcherDefinition[] watcherDefinitions = new WatcherDefinition[latches.length];
for (int i = 0; i < replicatedMaps.length; i++) {
ReplicatedMap replicatedMap = replicatedMaps[i];
CountDownLatch latch = new CountDownLatch(latches[i]);
WatcherListener listener = new WatcherListener(latch, eventType);
watcherDefinitions[i] = new WatcherDefinition(latch, replicatedMap, listener);
registrationIds[i] = replicatedMap.addEntryListener(listener);
}
try {
runnable.run();
long deadline = TimeUnit.SECONDS.toNanos(timeoutSeconds);
for (WatcherDefinition definition : watcherDefinitions) {
long start = System.nanoTime();
definition.await(deadline, TimeUnit.NANOSECONDS);
deadline -= System.nanoTime() - start;
if (deadline <= 0) {
throw new TimeoutException("Deadline reached. Remaining: "+definition.latch.getCount());
}
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
for (int i = 0; i < replicatedMaps.length; i++) {
ReplicatedMap replicatedMap = replicatedMaps[i];
replicatedMap.removeEntryListener(registrationIds[i]);
}
}
}