Skip to content

Commit 7488dc0

Browse files
javachefacebook-github-bot
authored andcommitted
Use CopyOnWriteArrayList in MemoryPressureRouter (#43486)
Summary: Pull Request resolved: #43486 We use `CopyOnWriteArrayList` in other places across the React Native codebase, as it assumes that reading happens more frequently than updating. This saves us from needing to synchronize and copy when we access the list of listeners. Changelog: [Internal] Reviewed By: sammy-SC Differential Revision: D54806272 fbshipit-source-id: d1b54d532edb2af3391a7e4fdc758f705621227d
1 parent a27e2ac commit 7488dc0

File tree

1 file changed

+8
-12
lines changed

1 file changed

+8
-12
lines changed

packages/react-native/ReactAndroid/src/main/java/com/facebook/react/MemoryPressureRouter.java

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,12 @@
1111
import android.content.Context;
1212
import android.content.res.Configuration;
1313
import com.facebook.react.bridge.MemoryPressureListener;
14-
import java.util.Collections;
15-
import java.util.LinkedHashSet;
16-
import java.util.Set;
14+
import java.util.concurrent.CopyOnWriteArrayList;
1715

18-
/** Translates and routes memory pressure events to the current catalyst instance. */
16+
/** Translates and routes memory pressure events. */
1917
public class MemoryPressureRouter implements ComponentCallbacks2 {
20-
private final Set<MemoryPressureListener> mListeners =
21-
Collections.synchronizedSet(new LinkedHashSet<>());
18+
private final CopyOnWriteArrayList<MemoryPressureListener> mListeners =
19+
new CopyOnWriteArrayList();
2220

2321
public MemoryPressureRouter(Context context) {
2422
context.getApplicationContext().registerComponentCallbacks(this);
@@ -30,7 +28,9 @@ public void destroy(Context context) {
3028

3129
/** Add a listener to be notified of memory pressure events. */
3230
public void addMemoryPressureListener(MemoryPressureListener listener) {
33-
mListeners.add(listener);
31+
if (!mListeners.contains(listener)) {
32+
mListeners.add(listener);
33+
}
3434
}
3535

3636
/** Remove a listener previously added with {@link #addMemoryPressureListener}. */
@@ -50,11 +50,7 @@ public void onConfigurationChanged(Configuration newConfig) {}
5050
public void onLowMemory() {}
5151

5252
private void dispatchMemoryPressure(int level) {
53-
// copy listeners array to avoid ConcurrentModificationException if any of the listeners remove
54-
// themselves in handleMemoryPressure()
55-
MemoryPressureListener[] listeners =
56-
mListeners.toArray(new MemoryPressureListener[mListeners.size()]);
57-
for (MemoryPressureListener listener : listeners) {
53+
for (MemoryPressureListener listener : mListeners) {
5854
listener.handleMemoryPressure(level);
5955
}
6056
}

0 commit comments

Comments
 (0)