Skip to content

Commit 5441168

Browse files
authored
Make ReactFontManager caches thread-safe
Summary: `ReactFontManager` keeps registered custom fonts and cached asset typefaces in plain maps and a `SparseArray` with no synchronization, but it is used from several threads at once: - Text measurement reads it on whichever thread calls `FabricUIManager.measure`, which is `AnyThread`. - Text spans and `ReactEditText` read it on the UI thread. - Apps can call `addCustomFont` from a background thread at any time, for example once a downloaded font file is ready. - `getTypeface()` itself writes the asset cache during a lookup. Concurrent use can drop entries, throw `ConcurrentModificationException` from `customFontFamilies`, or leave a reader with a stale or corrupted map. This switches both maps to `ConcurrentHashMap`, creates asset-family entries with `computeIfAbsent`, reads a custom font with one `get` instead of `containsKey` then `get`, and synchronizes the small per-family `SparseArray`. Behavior is otherwise unchanged. The maps never held null values (`addCustomFont` already ignores null), and the public API is the same. `ConcurrentHashMap` publishes each write to later readers, `computeIfAbsent` is available at the minimum SDK (24), and no lock is held while a typeface is created. Two threads that miss the asset cache at the same time can still both create the same typeface, with the last write kept, as before. Changelog: [Android][Fixed] - Make `ReactFontManager` safe to use from multiple threads Differential Revision: D129482043 Pull Request resolved: #59900
1 parent 339e09f commit 5441168

2 files changed

Lines changed: 86 additions & 7 deletions

File tree

‎packages/react-native/ReactAndroid/src/main/java/com/facebook/react/common/assets/ReactFontManager.kt‎

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import android.util.SparseArray
1616
import androidx.core.content.res.ResourcesCompat
1717
import com.facebook.react.common.ReactConstants
1818
import com.facebook.react.common.build.ReactBuildConfig
19+
import java.util.concurrent.ConcurrentHashMap
1920

2021
/**
2122
* Responsible for loading and caching Typeface objects.
@@ -32,8 +33,9 @@ import com.facebook.react.common.build.ReactBuildConfig
3233
*/
3334
public class ReactFontManager {
3435

35-
private val fontCache: MutableMap<String, AssetFontFamily> = mutableMapOf()
36-
private val customTypefaceCache: MutableMap<String, Typeface> = mutableMapOf()
36+
// Read during text layout on any thread and written by font registration from other threads.
37+
private val fontCache: ConcurrentHashMap<String, AssetFontFamily> = ConcurrentHashMap()
38+
private val customTypefaceCache: ConcurrentHashMap<String, Typeface> = ConcurrentHashMap()
3739

3840
/** The set of font family names that have been registered via [addCustomFont]. */
3941
public val customFontFamilies: Set<String>
@@ -64,13 +66,14 @@ public class ReactFontManager {
6466
typefaceStyle: TypefaceStyle,
6567
assetManager: AssetManager?,
6668
): Typeface {
67-
if (customTypefaceCache.containsKey(fontFamilyName)) {
69+
val customTypeface = customTypefaceCache[fontFamilyName]
70+
if (customTypeface != null) {
6871
// Apply `typefaceStyle` because custom fonts configure variants using `app:fontStyle` and
6972
// `app:fontWeight` in their resource XML configuration file.
70-
return typefaceStyle.apply(customTypefaceCache[fontFamilyName])
73+
return typefaceStyle.apply(customTypeface)
7174
}
7275

73-
val assetFontFamily = fontCache.getOrPut(fontFamilyName) { AssetFontFamily() }
76+
val assetFontFamily = fontCache.computeIfAbsent(fontFamilyName) { AssetFontFamily() }
7477
val style = typefaceStyle.nearestStyle
7578
return assetFontFamily.getTypefaceForStyle(style)
7679
?: createAssetTypeface(fontFamilyName, style, assetManager).also {
@@ -109,7 +112,9 @@ public class ReactFontManager {
109112
*/
110113
public fun setTypeface(fontFamilyName: String, style: Int, typeface: Typeface?) {
111114
if (typeface != null) {
112-
fontCache.getOrPut(fontFamilyName) { AssetFontFamily() }.setTypefaceForStyle(style, typeface)
115+
fontCache
116+
.computeIfAbsent(fontFamilyName) { AssetFontFamily() }
117+
.setTypefaceForStyle(style, typeface)
113118
}
114119
}
115120

@@ -205,8 +210,9 @@ public class ReactFontManager {
205210
private class AssetFontFamily {
206211
private val typefaceSparseArray: SparseArray<Typeface?> = SparseArray(4)
207212

208-
fun getTypefaceForStyle(style: Int): Typeface? = typefaceSparseArray[style]
213+
@Synchronized fun getTypefaceForStyle(style: Int): Typeface? = typefaceSparseArray[style]
209214

215+
@Synchronized
210216
fun setTypefaceForStyle(style: Int, typeface: Typeface?) {
211217
typefaceSparseArray.put(style, typeface)
212218
}
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/*
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*/
7+
8+
package com.facebook.react.common.assets
9+
10+
import android.graphics.Typeface
11+
import java.util.concurrent.CountDownLatch
12+
import java.util.concurrent.Executors
13+
import java.util.concurrent.TimeUnit
14+
import org.assertj.core.api.Assertions.assertThat
15+
import org.junit.Test
16+
import org.junit.runner.RunWith
17+
import org.robolectric.RobolectricTestRunner
18+
19+
@RunWith(RobolectricTestRunner::class)
20+
class ReactFontManagerTest {
21+
22+
@Test
23+
fun getTypeface_returnsRegisteredCustomFont() {
24+
val fontManager = ReactFontManager()
25+
26+
fontManager.addCustomFont("CustomFont", Typeface.SERIF)
27+
28+
assertThat(fontManager.customFontFamilies).containsExactly("CustomFont")
29+
assertThat(fontManager.getTypeface("CustomFont", Typeface.NORMAL, null)).isNotNull()
30+
}
31+
32+
@Test
33+
fun addCustomFont_ignoresNullTypeface() {
34+
val fontManager = ReactFontManager()
35+
36+
fontManager.addCustomFont("CustomFont", null)
37+
38+
assertThat(fontManager.customFontFamilies).isEmpty()
39+
}
40+
41+
@Test
42+
fun concurrentRegistrationAndLookup_keepsEveryFont() {
43+
val fontManager = ReactFontManager()
44+
val threadCount = 8
45+
val fontsPerThread = 200
46+
val executor = Executors.newFixedThreadPool(threadCount)
47+
val start = CountDownLatch(1)
48+
val errors = mutableListOf<Throwable>()
49+
50+
val futures =
51+
(0 until threadCount).map { thread ->
52+
executor.submit {
53+
start.await()
54+
try {
55+
for (i in 0 until fontsPerThread) {
56+
fontManager.addCustomFont("Custom $thread $i", Typeface.SERIF)
57+
fontManager.getTypeface("Custom $thread $i", Typeface.BOLD, null)
58+
fontManager.getTypeface("Asset $thread $i", Typeface.NORMAL, null)
59+
fontManager.customFontFamilies
60+
}
61+
} catch (e: Throwable) {
62+
synchronized(errors) { errors.add(e) }
63+
}
64+
}
65+
}
66+
start.countDown()
67+
futures.forEach { it.get(30, TimeUnit.SECONDS) }
68+
executor.shutdown()
69+
70+
assertThat(errors).isEmpty()
71+
assertThat(fontManager.customFontFamilies).hasSize(threadCount * fontsPerThread)
72+
}
73+
}

0 commit comments

Comments
 (0)