Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
* 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.queue

/**
* Splits the messages of a [MessageQueueThreadHandler] into bursts and reports how long each burst
* took. A burst is the run of messages handled back to back until the queue has nothing left that
* is due.
*
* A burst's duration is reported when the next burst starts, not when it ends. The performance hint
* service drops a session's boost when no reports arrive for a while, so a report sent at the end
* of a burst has usually expired by the time the next burst starts. Sent when work resumes, it
* applies to the work that is starting. Work that keeps the queue busy for longer than
* [longWorkNanos] is also reported while it runs.
*/
internal class MessageQueueThreadBurstTracker(
private val longWorkNanos: Long,
private val nanoTime: () -> Long,
private val isQueueIdle: () -> Boolean,
private val report: (durationNanos: Long) -> Unit,
) : MessageQueueThreadHandler.DispatchListener {
private var inBurst = false
private var burstStartNanos = 0L
private var unreportedNanos = 0L

override fun onMessageStart() {
if (inBurst) {
return
}
inBurst = true
burstStartNanos = nanoTime()
if (unreportedNanos > 0) {
report(minOf(unreportedNanos, MAX_REPORTED_NANOS))
unreportedNanos = 0L
}
}

override fun onMessageEnd() {
if (!inBurst) {
return
}
val now = nanoTime()
val elapsed = now - burstStartNanos
if (isQueueIdle()) {
inBurst = false
unreportedNanos = elapsed
} else if (elapsed >= longWorkNanos) {
report(minOf(elapsed, MAX_REPORTED_NANOS))
burstStartNanos = now
}
}

private companion object {
/** Caps a single report, in case a burst stays open across an idle period. */
const val MAX_REPORTED_NANOS = 1_000_000_000L
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,25 @@ internal class MessageQueueThreadHandler(
looper: Looper,
private val exceptionHandler: QueueThreadExceptionHandler,
) : Handler(looper) {
/** Observes every message this handler dispatches. */
interface DispatchListener {
fun onMessageStart()

fun onMessageEnd()
}

/** Set and read only on the looper's thread. */
var dispatchListener: DispatchListener? = null

override fun dispatchMessage(msg: Message) {
val listener = dispatchListener
listener?.onMessageStart()
try {
super.dispatchMessage(msg)
} catch (e: Exception) {
exceptionHandler.handleException(e)
} finally {
listener?.onMessageEnd()
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@

package com.facebook.react.bridge.queue

import android.content.Context
import android.os.Build
import android.os.Looper
import android.os.Process
import androidx.annotation.RequiresApi
import com.facebook.common.logging.FLog
import com.facebook.proguard.annotations.DoNotStripAny
import com.facebook.react.bridge.AssertionException
Expand All @@ -33,6 +36,8 @@ private constructor(

@Volatile private var isFinished = false

@Volatile private var performanceHint: MessageQueueThreadPerformanceHint? = null

/**
* Runs the given Runnable on this Thread. It will be submitted to the end of the event queue even
* if it is being submitted from the same queue Thread.
Expand Down Expand Up @@ -95,15 +100,50 @@ private constructor(
override fun quitSynchronous() {
isFinished = true
looper.quit()
if (looper.thread !== Thread.currentThread()) {
try {
looper.thread.join()
} catch (e: InterruptedException) {
throw RuntimeException("Got interrupted waiting to join thread $name")
try {
if (looper.thread !== Thread.currentThread()) {
try {
looper.thread.join()
} catch (e: InterruptedException) {
throw RuntimeException("Got interrupted waiting to join thread $name")
}
}
} finally {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
performanceHint?.close()
performanceHint = null
}
}
}

/**
* Reports this thread's bursts of work to Android's performance hint API, so that the system can
* run long work faster. Does nothing before Android 12, on the main thread, or on devices without
* hint support.
*/
internal fun enablePerformanceHint(context: Context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S || looper == Looper.getMainLooper()) {
return
}
val appContext = context.applicationContext
runOnQueue {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
installPerformanceHint(appContext)
}
}
}

@RequiresApi(Build.VERSION_CODES.S)
private fun installPerformanceHint(context: Context) {
if (performanceHint != null || isFinished) {
return
}
val hint =
MessageQueueThreadPerformanceHint.createForCurrentThread(context, looper.queue) ?: return
performanceHint = hint
handler.dispatchListener = hint.burstTracker
}

public override fun isIdle(): Boolean = looper.queue.isIdle

public companion object {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/*
* 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.queue

import android.content.Context
import android.os.Build
import android.os.MessageQueue
import android.os.PerformanceHintManager
import android.os.Process
import androidx.annotation.RequiresApi
import com.facebook.common.logging.FLog
import com.facebook.react.common.ReactConstants
import kotlin.concurrent.Volatile

/**
* Reports the work of a [MessageQueueThreadImpl] to Android's performance hint API (ADPF), so that
* the system can move the thread to a faster core, or raise its frequency, when its work takes
* longer than the target.
*
* The JS thread works in short bursts, such as one React update, separated by idle time. The
* scheduler sees a mostly idle thread and keeps it on slow cores. See
* [MessageQueueThreadBurstTracker] for how bursts are reported. Each report is the duration of the
* previous burst, sent when new work starts: Java has no public API to say that work is starting
* (`Session.sendHint` is hidden, and `APerformanceHint_notifyWorkloadIncrease` is NDK-only on
* Android 16+). Durations are wall time, so they also include time the thread spends blocked.
*/
@RequiresApi(Build.VERSION_CODES.S)
internal class MessageQueueThreadPerformanceHint
private constructor(private val session: PerformanceHintManager.Session, queue: MessageQueue) {
@Volatile private var closed = false

val burstTracker: MessageQueueThreadBurstTracker =
MessageQueueThreadBurstTracker(
longWorkNanos = TARGET_WORK_DURATION_NANOS,
nanoTime = System::nanoTime,
isQueueIdle = queue::isIdle,
report = ::report,
)

private fun report(durationNanos: Long) {
if (closed) {
return
}
try {
session.reportActualWorkDuration(durationNanos)
} catch (e: RuntimeException) {
FLog.w(ReactConstants.TAG, "Stopping performance hints after a failed report", e)
close()
}
}

fun close() {
if (!closed) {
closed = true
session.close()
}
}

companion object {
/**
* Half a 60 Hz frame. A burst that takes longer leaves too little of the frame to mount and
* draw its result, so the system is asked to run the thread faster.
*/
private const val TARGET_WORK_DURATION_NANOS = 8_000_000L

/**
* Creates a hint session for the calling thread, which must be the thread that runs [queue].
* Returns null when the device does not support performance hints.
*/
fun createForCurrentThread(
context: Context,
queue: MessageQueue,
): MessageQueueThreadPerformanceHint? {
return try {
val manager = context.getSystemService(PerformanceHintManager::class.java) ?: return null
val session =
manager.createHintSession(intArrayOf(Process.myTid()), TARGET_WORK_DURATION_NANOS)
?: return null
MessageQueueThreadPerformanceHint(session, queue)
} catch (e: RuntimeException) {
FLog.w(ReactConstants.TAG, "Could not create a performance hint session", e)
null
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<3a6a61e2cc2bf01a35ab5c3919462ad5>>
* @generated SignedSource<<503fc5939ddbab4a820219beaa95c9e4>>
*/

/**
Expand Down Expand Up @@ -288,6 +288,12 @@ public object ReactNativeFeatureFlags {
@JvmStatic
public fun enableIntersectionObserverByDefault(): Boolean = accessor.enableIntersectionObserverByDefault()

/**
* Reports bursts of work on the JS thread to the Android performance hint API (ADPF), so that the system runs long JS work on faster cores.
*/
@JvmStatic
public fun enableJSThreadPerformanceHintAndroid(): Boolean = accessor.enableJSThreadPerformanceHintAndroid()

/**
* Enables key up/down/press events to be sent to JS from components
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<fe927f4acf804e05b74dbe606e39746f>>
* @generated SignedSource<<b352f2731ba7847be735bb7e8dfb4a56>>
*/

/**
Expand Down Expand Up @@ -63,6 +63,7 @@ internal class ReactNativeFeatureFlagsCxxAccessor : ReactNativeFeatureFlagsAcces
private var enableInteractiveInlineButtonsCache: Boolean? = null
private var enableInteropViewManagerClassLookUpOptimizationIOSCache: Boolean? = null
private var enableIntersectionObserverByDefaultCache: Boolean? = null
private var enableJSThreadPerformanceHintAndroidCache: Boolean? = null
private var enableKeyEventsCache: Boolean? = null
private var enableLayoutAnimationsOnAndroidCache: Boolean? = null
private var enableLayoutAnimationsOnIOSCache: Boolean? = null
Expand Down Expand Up @@ -512,6 +513,15 @@ internal class ReactNativeFeatureFlagsCxxAccessor : ReactNativeFeatureFlagsAcces
return cached
}

override fun enableJSThreadPerformanceHintAndroid(): Boolean {
var cached = enableJSThreadPerformanceHintAndroidCache
if (cached == null) {
cached = ReactNativeFeatureFlagsCxxInterop.enableJSThreadPerformanceHintAndroid()
enableJSThreadPerformanceHintAndroidCache = cached
}
return cached
}

override fun enableKeyEvents(): Boolean {
var cached = enableKeyEventsCache
if (cached == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<b58702a0f594f409c0d20fd497395fde>>
* @generated SignedSource<<355ef0d59b9408bd94e30cd721eddea8>>
*/

/**
Expand Down Expand Up @@ -114,6 +114,8 @@ public object ReactNativeFeatureFlagsCxxInterop {

@DoNotStrip @JvmStatic public external fun enableIntersectionObserverByDefault(): Boolean

@DoNotStrip @JvmStatic public external fun enableJSThreadPerformanceHintAndroid(): Boolean

@DoNotStrip @JvmStatic public external fun enableKeyEvents(): Boolean

@DoNotStrip @JvmStatic public external fun enableLayoutAnimationsOnAndroid(): Boolean
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<834b0e9533cbc775a1c12b86140d718d>>
* @generated SignedSource<<9498681038c0d4d67d8f399aef534b51>>
*/

/**
Expand Down Expand Up @@ -109,6 +109,8 @@ public open class ReactNativeFeatureFlagsDefaults : ReactNativeFeatureFlagsProvi

override fun enableIntersectionObserverByDefault(): Boolean = false

override fun enableJSThreadPerformanceHintAndroid(): Boolean = false

override fun enableKeyEvents(): Boolean = false

override fun enableLayoutAnimationsOnAndroid(): Boolean = false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<15c65d4497fd9f36f8902efb2812b3b2>>
* @generated SignedSource<<b7da90aaed64f2153cf98cb77f7eb756>>
*/

/**
Expand Down Expand Up @@ -67,6 +67,7 @@ internal class ReactNativeFeatureFlagsLocalAccessor : ReactNativeFeatureFlagsAcc
private var enableInteractiveInlineButtonsCache: Boolean? = null
private var enableInteropViewManagerClassLookUpOptimizationIOSCache: Boolean? = null
private var enableIntersectionObserverByDefaultCache: Boolean? = null
private var enableJSThreadPerformanceHintAndroidCache: Boolean? = null
private var enableKeyEventsCache: Boolean? = null
private var enableLayoutAnimationsOnAndroidCache: Boolean? = null
private var enableLayoutAnimationsOnIOSCache: Boolean? = null
Expand Down Expand Up @@ -559,6 +560,16 @@ internal class ReactNativeFeatureFlagsLocalAccessor : ReactNativeFeatureFlagsAcc
return cached
}

override fun enableJSThreadPerformanceHintAndroid(): Boolean {
var cached = enableJSThreadPerformanceHintAndroidCache
if (cached == null) {
cached = currentProvider.enableJSThreadPerformanceHintAndroid()
accessedFeatureFlags.add("enableJSThreadPerformanceHintAndroid")
enableJSThreadPerformanceHintAndroidCache = cached
}
return cached
}

override fun enableKeyEvents(): Boolean {
var cached = enableKeyEventsCache
if (cached == null) {
Expand Down
Loading
Loading