[wpilib] Throw early when EventLoop is modified while running (#6115)

This commit is contained in:
Thad House
2023-12-31 22:45:10 -08:00
committed by GitHub
parent c16946c0ec
commit f9aabc5ab2
5 changed files with 91 additions and 1 deletions

View File

@@ -5,6 +5,7 @@
package edu.wpi.first.wpilibj.event;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.LinkedHashSet;
/**
@@ -12,6 +13,7 @@ import java.util.LinkedHashSet;
*/
public final class EventLoop {
private final Collection<Runnable> m_bindings = new LinkedHashSet<>();
private boolean m_running;
/**
* Bind a new action to run when the loop is polled.
@@ -19,16 +21,27 @@ public final class EventLoop {
* @param action the action to run.
*/
public void bind(Runnable action) {
if (m_running) {
throw new ConcurrentModificationException("Cannot bind EventLoop while it is running");
}
m_bindings.add(action);
}
/** Poll all bindings. */
public void poll() {
m_bindings.forEach(Runnable::run);
try {
m_running = true;
m_bindings.forEach(Runnable::run);
} finally {
m_running = false;
}
}
/** Clear all bindings. */
public void clear() {
if (m_running) {
throw new ConcurrentModificationException("Cannot clear EventLoop while it is running");
}
m_bindings.clear();
}
}