1616
1717package io .appium .java_client .proxy ;
1818
19- import lombok .AccessLevel ;
2019import lombok .AllArgsConstructor ;
2120import lombok .Getter ;
22- import lombok .NoArgsConstructor ;
2321import lombok .Setter ;
2422
2523import java .lang .ref .WeakReference ;
24+ import java .time .Duration ;
2625import java .util .Collection ;
2726import java .util .Collections ;
2827import java .util .LinkedList ;
2928import java .util .List ;
29+ import java .util .Timer ;
30+ import java .util .TimerTask ;
3031import java .util .concurrent .Semaphore ;
3132
32- @ NoArgsConstructor (access = AccessLevel .PRIVATE )
3333class ProxyListenersContainer {
34+ private static final Duration LISTENERS_CLEANUP_INTERVAL = Duration .ofMinutes (1 );
35+
3436 private static ProxyListenersContainer INSTANCE ;
3537
3638 public static synchronized ProxyListenersContainer getInstance () {
@@ -40,6 +42,21 @@ public static synchronized ProxyListenersContainer getInstance() {
4042 return INSTANCE ;
4143 }
4244
45+ private ProxyListenersContainer () {
46+ var task = new TimerTask () {
47+ @ Override
48+ public void run () {
49+ getListeners (null );
50+ }
51+ };
52+ // Listeners are cleaned up lazily, e.g. every time getListeners API
53+ // is called we also remove garbage-collected items. Although, due to an
54+ // unpredictable nature of the garbage collector and no guarantees about the
55+ // frequency of getListeners API calls we schedule the below loop to be executed every
56+ // minute, and make sure there are no extra references to obsolete listeners
57+ new Timer ().scheduleAtFixedRate (task , 0 , LISTENERS_CLEANUP_INTERVAL .toMillis ());
58+ }
59+
4360 private final Semaphore listenersGuard = new Semaphore (1 );
4461 private final List <Pair <WeakReference <?>, Collection <MethodCallListener >>> listenerPairs = new LinkedList <>();
4562
@@ -55,7 +72,7 @@ private static class Pair<K, V> {
5572 * Assign listeners for the particular proxied instance.
5673 *
5774 * @param proxyInstance The proxied instance.
58- * @param listeners Collection of listeners.
75+ * @param listeners Collection of listeners.
5976 * @return The same given instance.
6077 */
6178 public <T > T setListeners (T proxyInstance , Collection <MethodCallListener > listeners ) {
0 commit comments