Skip to content

Commit 2bd4480

Browse files
chore: Perform listeners cleanup periodically (#2077)
1 parent b082b37 commit 2bd4480

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

src/main/java/io/appium/java_client/proxy/ProxyListenersContainer.java

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,21 +16,23 @@
1616

1717
package io.appium.java_client.proxy;
1818

19-
import lombok.AccessLevel;
2019
import lombok.AllArgsConstructor;
2120
import lombok.Getter;
22-
import lombok.NoArgsConstructor;
2321
import lombok.Setter;
2422

2523
import java.lang.ref.WeakReference;
24+
import java.time.Duration;
2625
import java.util.Collection;
2726
import java.util.Collections;
2827
import java.util.LinkedList;
2928
import java.util.List;
29+
import java.util.Timer;
30+
import java.util.TimerTask;
3031
import java.util.concurrent.Semaphore;
3132

32-
@NoArgsConstructor(access = AccessLevel.PRIVATE)
3333
class 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

Comments
 (0)