Skip to content

Commit 9522db3

Browse files
authored
Merge pull request #10910 from woocommerce/fix/weakref-concurrent-modification
Fix ProductImageMap ConcurrentModificationException by Safely Managing WeakReferences
2 parents 24ffc7e + 49a6057 commit 9522db3

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

WooCommerce/src/main/kotlin/com/woocommerce/android/tools/ProductImageMap.kt

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ import kotlinx.coroutines.withContext
88
import org.wordpress.android.fluxc.store.WCProductStore
99
import org.wordpress.android.fluxc.store.WCProductStore.FetchSingleProductPayload
1010
import java.lang.ref.WeakReference
11-
import java.util.concurrent.CopyOnWriteArrayList
1211
import javax.inject.Inject
1312
import javax.inject.Singleton
1413

@@ -28,7 +27,7 @@ class ProductImageMap @Inject constructor(
2827
fun onProductFetched(remoteProductId: Long)
2928
}
3029

31-
private val observers: MutableList<WeakReference<OnProductFetchedListener>> = CopyOnWriteArrayList()
30+
private val observers: MutableList<WeakReference<OnProductFetchedListener>> = mutableListOf()
3231

3332
private val map by lazy {
3433
HashMap<Long, String>()
@@ -64,12 +63,14 @@ class ProductImageMap @Inject constructor(
6463
val result = productStore.fetchSingleProduct(FetchSingleProductPayload(site, remoteProductId))
6564
if (!result.isError) {
6665
withContext(dispatchers.main) {
66+
// Collect references to remove
67+
val toRemove = mutableListOf<WeakReference<OnProductFetchedListener>>()
6768
observers.forEach { weakReference ->
68-
// notify the observer
69-
weakReference.get()?.onProductFetched(remoteProductId)
70-
// remove the weak reference if the observer was garbage collected
71-
?: observers.remove(weakReference)
69+
// notify the observer or collect it for removal if it's been garbage collected
70+
weakReference.get()?.onProductFetched(remoteProductId) ?: toRemove.add(weakReference)
7271
}
72+
// Remove the collected references
73+
observers.removeAll(toRemove)
7374
}
7475
}
7576
}

0 commit comments

Comments
 (0)