16
16
17
17
package io .appium .java_client .proxy ;
18
18
19
- import lombok .AccessLevel ;
20
19
import lombok .AllArgsConstructor ;
21
20
import lombok .Getter ;
22
- import lombok .NoArgsConstructor ;
23
21
import lombok .Setter ;
24
22
25
23
import java .lang .ref .WeakReference ;
24
+ import java .time .Duration ;
26
25
import java .util .Collection ;
27
26
import java .util .Collections ;
28
27
import java .util .LinkedList ;
29
28
import java .util .List ;
29
+ import java .util .Timer ;
30
+ import java .util .TimerTask ;
30
31
import java .util .concurrent .Semaphore ;
31
32
32
- @ NoArgsConstructor (access = AccessLevel .PRIVATE )
33
33
class ProxyListenersContainer {
34
+ private static final Duration LISTENERS_CLEANUP_INTERVAL = Duration .ofMinutes (1 );
35
+
34
36
private static ProxyListenersContainer INSTANCE ;
35
37
36
38
public static synchronized ProxyListenersContainer getInstance () {
@@ -40,6 +42,21 @@ public static synchronized ProxyListenersContainer getInstance() {
40
42
return INSTANCE ;
41
43
}
42
44
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
+
43
60
private final Semaphore listenersGuard = new Semaphore (1 );
44
61
private final List <Pair <WeakReference <?>, Collection <MethodCallListener >>> listenerPairs = new LinkedList <>();
45
62
@@ -55,7 +72,7 @@ private static class Pair<K, V> {
55
72
* Assign listeners for the particular proxied instance.
56
73
*
57
74
* @param proxyInstance The proxied instance.
58
- * @param listeners Collection of listeners.
75
+ * @param listeners Collection of listeners.
59
76
* @return The same given instance.
60
77
*/
61
78
public <T > T setListeners (T proxyInstance , Collection <MethodCallListener > listeners ) {
0 commit comments