diff --git a/java/src/org/openqa/selenium/bidi/Connection.java b/java/src/org/openqa/selenium/bidi/Connection.java index 643872ed1f0e3..9b667eee627dc 100644 --- a/java/src/org/openqa/selenium/bidi/Connection.java +++ b/java/src/org/openqa/selenium/bidi/Connection.java @@ -25,6 +25,7 @@ import java.io.Closeable; import java.io.StringReader; import java.time.Duration; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -210,7 +211,16 @@ public void removeListener(long id) { Lock lock = callbacksLock.writeLock(); lock.lock(); try { - eventCallbacks.forEach((k, v) -> v.remove(id)); + List> list = new ArrayList<>(); + eventCallbacks.forEach( + (k, v) -> { + v.remove(id); + if (v.isEmpty()) { + list.add(k); + } + }); + + list.forEach(eventCallbacks::remove); } finally { lock.unlock(); }