From b0530f0abfef2b8bb7d6fdee5f6aac3188733c95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateo=20Guzm=C3=A1n?= Date: Fri, 13 Jun 2025 10:46:44 -0700 Subject: [PATCH] Migrate `ModuleHolder` to Kotlin (#51997) Summary: Migrate com.facebook.react.bridge.ModuleHolder to Kotlin. ## Changelog: [INTERNAL] - Migrate com.facebook.react.bridge.ModuleHolder to Kotlin Pull Request resolved: https://github.com/facebook/react-native/pull/51997 Test Plan: ```bash yarn test-android yarn android ``` Reviewed By: javache Differential Revision: D76591704 Pulled By: cortinico fbshipit-source-id: adbf1375ae9999881ce75b7d73d8e0bb3a8a73f8 --- .../ReactAndroid/api/ReactAndroid.api | 16 +- .../facebook/react/bridge/ModuleHolder.java | 247 ------------------ .../com/facebook/react/bridge/ModuleHolder.kt | 226 ++++++++++++++++ 3 files changed, 234 insertions(+), 255 deletions(-) delete mode 100644 packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ModuleHolder.java create mode 100644 packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ModuleHolder.kt diff --git a/packages/react-native/ReactAndroid/api/ReactAndroid.api b/packages/react-native/ReactAndroid/api/ReactAndroid.api index dc6634efe6d..f8082a886b3 100644 --- a/packages/react-native/ReactAndroid/api/ReactAndroid.api +++ b/packages/react-native/ReactAndroid/api/ReactAndroid.api @@ -950,16 +950,16 @@ public abstract interface class com/facebook/react/bridge/MemoryPressureListener public abstract fun handleMemoryPressure (I)V } -public class com/facebook/react/bridge/ModuleHolder { +public final class com/facebook/react/bridge/ModuleHolder { public fun (Lcom/facebook/react/bridge/NativeModule;)V public fun (Lcom/facebook/react/module/model/ReactModuleInfo;Ljavax/inject/Provider;)V - public fun destroy ()V - public fun getCanOverrideExistingModule ()Z - public fun getClassName ()Ljava/lang/String; - public fun getModule ()Lcom/facebook/react/bridge/NativeModule; - public fun getName ()Ljava/lang/String; - public fun isCxxModule ()Z - public fun isTurboModule ()Z + public final fun destroy ()V + public final fun getCanOverrideExistingModule ()Z + public final fun getClassName ()Ljava/lang/String; + public final fun getModule ()Lcom/facebook/react/bridge/NativeModule; + public final fun getName ()Ljava/lang/String; + public final fun isCxxModule ()Z + public final fun isTurboModule ()Z } public final class com/facebook/react/bridge/ModuleSpec { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ModuleHolder.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ModuleHolder.java deleted file mode 100644 index 2ee126b4d40..00000000000 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ModuleHolder.java +++ /dev/null @@ -1,247 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -package com.facebook.react.bridge; - -import static com.facebook.infer.annotation.Assertions.assertNotNull; -import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_MODULE_END; -import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_MODULE_START; -import static com.facebook.systrace.Systrace.TRACE_TAG_REACT; - -import androidx.annotation.GuardedBy; -import androidx.annotation.Nullable; -import com.facebook.common.logging.FLog; -import com.facebook.debug.holder.PrinterHolder; -import com.facebook.debug.tags.ReactDebugOverlayTags; -import com.facebook.infer.annotation.Assertions; -import com.facebook.infer.annotation.Nullsafe; -import com.facebook.proguard.annotations.DoNotStrip; -import com.facebook.react.common.ReactConstants; -import com.facebook.react.module.model.ReactModuleInfo; -import com.facebook.systrace.SystraceMessage; -import java.util.concurrent.atomic.AtomicInteger; -import javax.inject.Provider; - -/** - * Holder to enable us to lazy create native modules. - * - *

This works by taking a provider instead of an instance, when it is first required we'll create - * and initialize it. Initialization currently always happens on the UI thread but this is due to - * change for performance reasons. - * - *

Lifecycle events via a {@link LifecycleEventListener} will still always happen on the UI - * thread. - */ -@Nullsafe(Nullsafe.Mode.LOCAL) -@DoNotStrip -public class ModuleHolder { - - private static final AtomicInteger sInstanceKeyCounter = new AtomicInteger(1); - - private final int mInstanceKey = sInstanceKeyCounter.getAndIncrement(); - - private final String mName; - private final ReactModuleInfo mReactModuleInfo; - - private @Nullable Provider mProvider; - // Outside of the constructor, these should only be checked or set when synchronized on this - private @Nullable @GuardedBy("this") NativeModule mModule; - - // These are used to communicate phases of creation and initialization across threads - private @GuardedBy("this") boolean mInitializable; - private @GuardedBy("this") boolean mIsCreating; - private @GuardedBy("this") boolean mIsInitializing; - - public ModuleHolder(ReactModuleInfo moduleInfo, Provider provider) { - mName = moduleInfo.name(); - mProvider = provider; - mReactModuleInfo = moduleInfo; - if (moduleInfo.needsEagerInit()) { - mModule = create(); - } - } - - public ModuleHolder(NativeModule nativeModule) { - mName = nativeModule.getName(); - mReactModuleInfo = - new ReactModuleInfo( - nativeModule.getName(), - nativeModule.getClass().getSimpleName(), - nativeModule.canOverrideExistingModule(), - true, - CxxModuleWrapper.class.isAssignableFrom(nativeModule.getClass()), - ReactModuleInfo.classIsTurboModule(nativeModule.getClass())); - - mModule = nativeModule; - PrinterHolder.getPrinter() - .logMessage(ReactDebugOverlayTags.NATIVE_MODULE, "NativeModule init: %s", mName); - } - - /* - * Checks if mModule has been created, and if so tries to initialize the module unless another - * thread is already doing the initialization. - * If mModule has not been created, records that initialization is needed - */ - /* package */ void markInitializable() { - boolean shouldInitializeNow = false; - NativeModule module = null; - synchronized (this) { - mInitializable = true; - if (mModule != null) { - Assertions.assertCondition(!mIsInitializing); - shouldInitializeNow = true; - module = mModule; - } - } - if (shouldInitializeNow) { - Assertions.assertNotNull(module); - doInitialize(module); - } - } - - /* package */ synchronized boolean hasInstance() { - return mModule != null; - } - - public synchronized void destroy() { - if (mModule != null) { - mModule.invalidate(); - } - } - - @DoNotStrip - public String getName() { - return mName; - } - - public boolean getCanOverrideExistingModule() { - return mReactModuleInfo.canOverrideExistingModule(); - } - - public boolean isTurboModule() { - return mReactModuleInfo.isTurboModule(); - } - - public boolean isCxxModule() { - return mReactModuleInfo.isCxxModule(); - } - - public String getClassName() { - return mReactModuleInfo.className(); - } - - @DoNotStrip - public NativeModule getModule() { - NativeModule module; - boolean shouldCreate = false; - synchronized (this) { - if (mModule != null) { - return mModule; - // if mModule has not been set, and no one is creating it. Then this thread should call - // create - } else if (!mIsCreating) { - shouldCreate = true; - mIsCreating = true; - } else { - // Wait for mModule to be created by another thread - } - } - if (shouldCreate) { - module = create(); - // Once module is built (and initialized if markInitializable has been called), modify mModule - // And signal any waiting threads that it is acceptable to read the field now - synchronized (this) { - mIsCreating = false; - this.notifyAll(); - } - return module; - } else { - synchronized (this) { - // Block waiting for another thread to build mModule instance - // Since mIsCreating is true until after creation and instantiation (if needed), we wait - // until the module is ready to use. - while (mModule == null && mIsCreating) { - try { - this.wait(); - } catch (InterruptedException e) { - continue; - } - } - return Assertions.assertNotNull(mModule); - } - } - } - - private NativeModule create() { - SoftAssertions.assertCondition(mModule == null, "Creating an already created module."); - ReactMarker.logMarker(CREATE_MODULE_START, mName, mInstanceKey); - SystraceMessage.beginSection(TRACE_TAG_REACT, "ModuleHolder.createModule") - .arg("name", mName) - .flush(); - PrinterHolder.getPrinter() - .logMessage(ReactDebugOverlayTags.NATIVE_MODULE, "NativeModule init: %s", mName); - NativeModule module; - try { - module = assertNotNull(mProvider).get(); - mProvider = null; - boolean shouldInitializeNow = false; - synchronized (this) { - mModule = module; - if (mInitializable && !mIsInitializing) { - shouldInitializeNow = true; - } - } - if (shouldInitializeNow) { - doInitialize(module); - } - } catch (Throwable ex) { - /** - * When NativeModules are created from JavaScript, any exception that occurs in the creation - * process will have its stack trace swallowed before we display a RedBox to the user. Really, - * we should have our HostObjects on Android understand JniExceptions and log the stack trace - * to logcat. For now, logging to Logcat directly when creation fails is sufficient. - * - * @todo(T53311351) - */ - FLog.e(ReactConstants.TAG, ex, "Failed to create NativeModule '%s'", mName); - throw ex; - } finally { - ReactMarker.logMarker(CREATE_MODULE_END, mName, mInstanceKey); - SystraceMessage.endSection(TRACE_TAG_REACT).flush(); - } - return module; - } - - private void doInitialize(NativeModule module) { - SystraceMessage.beginSection(TRACE_TAG_REACT, "ModuleHolder.initialize") - .arg("name", mName) - .flush(); - ReactMarker.logMarker(ReactMarkerConstants.INITIALIZE_MODULE_START, mName, mInstanceKey); - try { - boolean shouldInitialize = false; - // Check to see if another thread is initializing the object, if not claim the responsibility - synchronized (this) { - if (mInitializable && !mIsInitializing) { - shouldInitialize = true; - mIsInitializing = true; - } - } - if (shouldInitialize) { - module.initialize(); - // Once finished, set flags accordingly, but we don't expect anyone to wait for this to - // finish - // So no need to notify other threads - synchronized (this) { - mIsInitializing = false; - } - } - } finally { - ReactMarker.logMarker(ReactMarkerConstants.INITIALIZE_MODULE_END, mName, mInstanceKey); - SystraceMessage.endSection(TRACE_TAG_REACT).flush(); - } - } -} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ModuleHolder.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ModuleHolder.kt new file mode 100644 index 00000000000..d6e12cc369f --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ModuleHolder.kt @@ -0,0 +1,226 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react.bridge + +import androidx.annotation.GuardedBy +import com.facebook.common.logging.FLog +import com.facebook.debug.holder.PrinterHolder +import com.facebook.debug.tags.ReactDebugOverlayTags +import com.facebook.proguard.annotations.DoNotStrip +import com.facebook.react.common.ReactConstants +import com.facebook.react.module.model.ReactModuleInfo +import com.facebook.systrace.Systrace.TRACE_TAG_REACT +import com.facebook.systrace.SystraceMessage +import java.util.concurrent.atomic.AtomicInteger +import javax.inject.Provider + +/** + * Holder to enable us to lazy create native modules. + * + * This works by taking a provider instead of an instance, when it is first required we'll create + * and initialize it. Initialization currently always happens on the UI thread but this is due to + * change for performance reasons. + * + * Lifecycle events via a [LifecycleEventListener] will still always happen on the UI thread. + */ +@DoNotStrip +public class ModuleHolder { + private val instanceKey = instanceKeyCounter.getAndIncrement() + @get:DoNotStrip public val name: String + private val reactModuleInfo: ReactModuleInfo + + private var provider: Provider? = null + // Outside of the constructor, this should only be checked or set when synchronized on this + @GuardedBy("this") private var internalModule: NativeModule? = null + // This is used to communicate phases of creation and initialization across threads + @GuardedBy("this") private var initializable = false + @GuardedBy("this") private var isCreating = false + @GuardedBy("this") private var isInitializing = false + + public constructor(moduleInfo: ReactModuleInfo, provider: Provider) { + name = moduleInfo.name + this.provider = provider + reactModuleInfo = moduleInfo + if (moduleInfo.needsEagerInit) { + internalModule = create() + } + } + + public constructor(nativeModule: NativeModule) { + name = nativeModule.name + reactModuleInfo = + ReactModuleInfo( + nativeModule.name, + nativeModule.javaClass.simpleName, + nativeModule.canOverrideExistingModule(), + true, + CxxModuleWrapper::class.java.isAssignableFrom(nativeModule.javaClass), + ReactModuleInfo.classIsTurboModule(nativeModule.javaClass)) + + internalModule = nativeModule + PrinterHolder.printer.logMessage( + ReactDebugOverlayTags.NATIVE_MODULE, "NativeModule init: %s", name) + } + + /* + * Checks if [internalModule] has been created, and if so tries to initialize the module unless another + * thread is already doing the initialization. + * If [internalModule] has not been created, records that initialization is needed. + */ + internal fun markInitializable() { + var shouldInitializeNow = false + var module: NativeModule? = null + synchronized(this) { + initializable = true + if (internalModule != null) { + check(!isInitializing) + shouldInitializeNow = true + module = internalModule + } + } + if (shouldInitializeNow) { + checkNotNull(module) + doInitialize(module) + } + } + + @Synchronized internal fun hasInstance(): Boolean = internalModule != null + + @Synchronized + public fun destroy() { + internalModule?.invalidate() + } + + public val canOverrideExistingModule: Boolean + get() = reactModuleInfo.canOverrideExistingModule + + public val isTurboModule: Boolean + get() = reactModuleInfo.isTurboModule + + public val isCxxModule: Boolean + get() = reactModuleInfo.isCxxModule + + public val className: String + get() = reactModuleInfo.className + + @get:DoNotStrip + public val module: NativeModule + get() { + val module: NativeModule + var shouldCreate = false + synchronized(this) { + val safeModule = internalModule + if (safeModule != null) { + return safeModule + // if `internalModule` has not been set, and no one is creating it. Then this thread + // should call + // create + } else if (!isCreating) { + shouldCreate = true + isCreating = true + } else { + // Wait for `internalModule` to be created by another thread + } + } + if (shouldCreate) { + module = create() + // Once module is built (and initialized if markInitializable has been called), modify + // `internalModule` + // And signal any waiting threads that it is acceptable to read the field now + synchronized(this) { + isCreating = false + @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") (this as Object).notifyAll() + } + return module + } else { + synchronized(this) { + // Block waiting for another thread to build `internalModule` instance + // Since isCreating is true until after creation and instantiation (if needed), we wait + // until the module is ready to use. + while (internalModule == null && isCreating) { + try { + @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") (this as Object).wait() + } catch (e: InterruptedException) { + continue + } + } + return checkNotNull(internalModule) + } + } + } + + private fun create(): NativeModule { + SoftAssertions.assertCondition(internalModule == null, "Creating an already created module.") + ReactMarker.logMarker(ReactMarkerConstants.CREATE_MODULE_START, name, instanceKey) + SystraceMessage.beginSection(TRACE_TAG_REACT, "ModuleHolder.createModule") + .arg("name", name) + .flush() + PrinterHolder.printer.logMessage( + ReactDebugOverlayTags.NATIVE_MODULE, "NativeModule init: %s", name) + val module: NativeModule + try { + module = checkNotNull(provider).get() + provider = null + var shouldInitializeNow = false + synchronized(this) { + internalModule = module + if (initializable && !isInitializing) { + shouldInitializeNow = true + } + } + if (shouldInitializeNow) { + doInitialize(module) + } + } catch (e: Throwable) { + /** + * When NativeModules are created from JavaScript, any exception that occurs in the creation + * process will have its stack trace swallowed before we display a RedBox to the user. Really, + * we should have our HostObjects on Android understand JniExceptions and log the stack trace + * to logcat. For now, logging to Logcat directly when creation fails is sufficient. + * + * @todo(T53311351) + */ + FLog.e(ReactConstants.TAG, e, "Failed to create NativeModule '%s'", name) + throw e + } finally { + ReactMarker.logMarker(ReactMarkerConstants.CREATE_MODULE_END, name, instanceKey) + SystraceMessage.endSection(TRACE_TAG_REACT).flush() + } + return module + } + + private fun doInitialize(module: NativeModule?) { + SystraceMessage.beginSection(TRACE_TAG_REACT, "ModuleHolder.initialize") + .arg("name", name) + .flush() + ReactMarker.logMarker(ReactMarkerConstants.INITIALIZE_MODULE_START, name, instanceKey) + try { + var shouldInitialize = false + // Check to see if another thread is initializing the object, if not claim the responsibility + synchronized(this) { + if (initializable && !isInitializing) { + shouldInitialize = true + isInitializing = true + } + } + if (shouldInitialize) { + module?.initialize() + // Once finished, set flags accordingly, but we don't expect anyone to wait for this to + // finish, so no need to notify other threads. + synchronized(this) { isInitializing = false } + } + } finally { + ReactMarker.logMarker(ReactMarkerConstants.INITIALIZE_MODULE_END, name, instanceKey) + SystraceMessage.endSection(TRACE_TAG_REACT).flush() + } + } + + private companion object { + private val instanceKeyCounter = AtomicInteger(1) + } +}