From c1102750ddbcad9ccf771fee7b6b574d95e6a13d Mon Sep 17 00:00:00 2001 From: Uwais Ashraf Date: Wed, 7 May 2025 15:27:19 +0000 Subject: [PATCH] Create separate worker threads for IO work and lighter BG work Documentation largely pulled from Kotlin coroutines docs. Flag: com.android.launcher3.enable_coroutine_threading_improvements Bug: 416206104 Test: Presubmits Change-Id: I89b7222e31680619e311fa9e9986da5c12d80ed4 --- .../dagger/LauncherConcurrencyModule.kt | 2 +- .../launcher3/dagger/PerDisplayModule.kt | 2 +- .../quickstep/OverviewCommandHelper.kt | 3 +- .../com/android/quickstep/TaskIconCache.kt | 36 +++++++--- .../android/quickstep/TaskThumbnailCache.kt | 47 ++++++++------ .../recents/data/AppTimersRepositoryImpl.kt | 2 +- .../quickstep/recents/data/TasksRepository.kt | 12 ++-- .../recents/ui/viewmodel/TaskViewModel.kt | 4 +- .../quickstep/views/RecentsViewModelHelper.kt | 5 +- .../com/android/quickstep/views/TaskView.kt | 2 +- .../util/coroutines/DispatcherProvider.kt | 65 +++++++++++++++---- .../launcher3/util/TestDispatcherProvider.kt | 3 +- 12 files changed, 127 insertions(+), 56 deletions(-) diff --git a/quickstep/src/com/android/launcher3/dagger/LauncherConcurrencyModule.kt b/quickstep/src/com/android/launcher3/dagger/LauncherConcurrencyModule.kt index 2d8da22187..fd10faae42 100644 --- a/quickstep/src/com/android/launcher3/dagger/LauncherConcurrencyModule.kt +++ b/quickstep/src/com/android/launcher3/dagger/LauncherConcurrencyModule.kt @@ -68,6 +68,6 @@ object LauncherConcurrencyModule { @Background fun provideBgCoroutineScope(dispatcherProvider: DispatcherProvider) = CoroutineScope( - SupervisorJob() + dispatcherProvider.background + CoroutineName("LauncherBg") + SupervisorJob() + dispatcherProvider.ioBackground + CoroutineName("LauncherBg") ) } diff --git a/quickstep/src/com/android/launcher3/dagger/PerDisplayModule.kt b/quickstep/src/com/android/launcher3/dagger/PerDisplayModule.kt index ee57bd636a..19fa1a8ca0 100644 --- a/quickstep/src/com/android/launcher3/dagger/PerDisplayModule.kt +++ b/quickstep/src/com/android/launcher3/dagger/PerDisplayModule.kt @@ -232,7 +232,7 @@ object DisplayLibModule { displayManager, bgHandler, bgApplicationScope, - coroutineDispatcherProvider.background, + coroutineDispatcherProvider.ioBackground, ) } diff --git a/quickstep/src/com/android/quickstep/OverviewCommandHelper.kt b/quickstep/src/com/android/quickstep/OverviewCommandHelper.kt index 8a1e37d5d4..faba8b1df2 100644 --- a/quickstep/src/com/android/quickstep/OverviewCommandHelper.kt +++ b/quickstep/src/com/android/quickstep/OverviewCommandHelper.kt @@ -82,7 +82,8 @@ constructor( private val taskAnimationManagerRepository: PerDisplayRepository, private val elapsedRealtime: () -> Long = SystemClock::elapsedRealtime, ) { - private val coroutineScope = CoroutineScope(SupervisorJob() + dispatcherProvider.background) + private val coroutineScope = + CoroutineScope(SupervisorJob() + dispatcherProvider.lightweightBackground) private val commandQueue = ConcurrentLinkedDeque() diff --git a/quickstep/src/com/android/quickstep/TaskIconCache.kt b/quickstep/src/com/android/quickstep/TaskIconCache.kt index ce808107a7..a03100e467 100644 --- a/quickstep/src/com/android/quickstep/TaskIconCache.kt +++ b/quickstep/src/com/android/quickstep/TaskIconCache.kt @@ -39,6 +39,9 @@ import com.android.launcher3.util.Executors import com.android.launcher3.util.FlagOp import com.android.launcher3.util.OverviewReleaseFlags.enableOverviewIconMenu import com.android.launcher3.util.Preconditions +import com.android.launcher3.util.coroutines.DispatcherProvider +import com.android.quickstep.recents.di.RecentsDependencies +import com.android.quickstep.recents.di.inject import com.android.quickstep.task.thumbnail.data.TaskIconDataSource import com.android.quickstep.util.IconLabelUtil.getBadgedContentDescription import com.android.quickstep.util.TaskKeyLruCache @@ -47,6 +50,7 @@ import com.android.systemui.shared.recents.model.Task import com.android.systemui.shared.recents.model.Task.TaskKey import com.android.systemui.shared.system.PackageManagerWrapper import java.util.concurrent.Executor +import kotlinx.coroutines.withContext /** Manages the caching of task icons and related data. */ class TaskIconCache( @@ -70,6 +74,7 @@ class TaskIconCache( else _iconFactory ?: createIconFactory().also { _iconFactory = it } var taskVisualsChangeListener: TaskVisualsChangeListener? = null + val dispatcherProvider: DispatcherProvider by RecentsDependencies.inject() init { // TODO (b/397205964): this will need to be updated when we support caches for different @@ -90,13 +95,20 @@ class TaskIconCache( return TaskCacheEntry(icon, task.titleDescription ?: "", task.title ?: "") } - val entry = getCacheEntry(task) - task.icon = entry.icon - task.titleDescription = entry.contentDescription - task.title = entry.title + // Return from cache if present + iconCache.getAndInvalidateIfModified(task.key)?.let { + return it + } - dispatchIconUpdate(task.key.id) - return entry + return withContext(dispatcherProvider.ioBackground) { + val entry = getCacheEntry(task) + task.icon = entry.icon + task.titleDescription = entry.contentDescription + task.title = entry.title + + dispatchIconUpdate(task.key.id) + return@withContext entry + } } /** @@ -113,6 +125,14 @@ class TaskIconCache( callback.onTaskIconReceived(it, task.titleDescription ?: "", task.title ?: "") return null } + iconCache.getAndInvalidateIfModified(task.key)?.let { + task.icon = it.icon + task.titleDescription = it.contentDescription + task.title = it.title + + callback.onTaskIconReceived(it.icon, it.contentDescription, it.title) + return null + } val request = CancellableTask( { getCacheEntry(task) }, @@ -161,10 +181,6 @@ class TaskIconCache( @WorkerThread private fun getCacheEntry(task: Task): TaskCacheEntry { - iconCache.getAndInvalidateIfModified(task.key)?.let { - return it - } - val desc = task.taskDescription val key = task.key var activityInfo: ActivityInfo? = null diff --git a/quickstep/src/com/android/quickstep/TaskThumbnailCache.kt b/quickstep/src/com/android/quickstep/TaskThumbnailCache.kt index fdead8fd09..1f16e21015 100644 --- a/quickstep/src/com/android/quickstep/TaskThumbnailCache.kt +++ b/quickstep/src/com/android/quickstep/TaskThumbnailCache.kt @@ -23,6 +23,9 @@ import com.android.launcher3.util.CancellableTask import com.android.launcher3.util.Executors import com.android.launcher3.util.OverviewReleaseFlags.enableGridOnlyOverview import com.android.launcher3.util.Preconditions +import com.android.launcher3.util.coroutines.DispatcherProvider +import com.android.quickstep.recents.di.RecentsDependencies +import com.android.quickstep.recents.di.inject import com.android.quickstep.task.thumbnail.data.TaskThumbnailDataSource import com.android.quickstep.util.TaskKeyByLastActiveTimeCache import com.android.quickstep.util.TaskKeyCache @@ -33,6 +36,7 @@ import com.android.systemui.shared.recents.model.ThumbnailData import com.android.systemui.shared.system.ActivityManagerWrapper import java.util.concurrent.Executor import java.util.function.Consumer +import kotlinx.coroutines.withContext class TaskThumbnailCache @VisibleForTesting @@ -44,6 +48,7 @@ internal constructor( val highResLoadingState = HighResLoadingState() private val enableTaskSnapshotPreloading = context.resources.getBoolean(R.bool.config_enableTaskSnapshotPreloading) + val dispatcherProvider: DispatcherProvider by RecentsDependencies.inject() @JvmOverloads constructor( @@ -104,27 +109,31 @@ internal constructor( return cachedThumbnail } - // Get thumbnail from system - var thumbnailData = - ActivityManagerWrapper.getInstance().getTaskThumbnail(task.key.id, lowResolution) - if (thumbnailData.thumbnail == null) { - thumbnailData = ActivityManagerWrapper.getInstance().takeTaskThumbnail(task.key.id) - } - - // Avoid an async timing issue that a low res entry replaces an existing high - // res entry in high res enabled state, so we check before putting it to cache - if ( - enableGridOnlyOverview() && - thumbnailData.reducedResolution && - highResLoadingState.isEnabled - ) { - val newCachedThumbnail = cache.getAndInvalidateIfModified(task.key) - if (newCachedThumbnail?.thumbnail != null && !newCachedThumbnail.reducedResolution) { - return newCachedThumbnail + return withContext(dispatcherProvider.ioBackground) { + // Get thumbnail from system + var thumbnailData = + ActivityManagerWrapper.getInstance().getTaskThumbnail(task.key.id, lowResolution) + if (thumbnailData.thumbnail == null) { + thumbnailData = ActivityManagerWrapper.getInstance().takeTaskThumbnail(task.key.id) } + + // Avoid an async timing issue that a low res entry replaces an existing high + // res entry in high res enabled state, so we check before putting it to cache + if ( + enableGridOnlyOverview() && + thumbnailData.reducedResolution && + highResLoadingState.isEnabled + ) { + val newCachedThumbnail = cache.getAndInvalidateIfModified(task.key) + if ( + newCachedThumbnail?.thumbnail != null && !newCachedThumbnail.reducedResolution + ) { + return@withContext newCachedThumbnail + } + } + cache.put(task.key, thumbnailData) + return@withContext thumbnailData } - cache.put(task.key, thumbnailData) - return thumbnailData } /** diff --git a/quickstep/src/com/android/quickstep/recents/data/AppTimersRepositoryImpl.kt b/quickstep/src/com/android/quickstep/recents/data/AppTimersRepositoryImpl.kt index b286a5b56d..930bbe44c6 100644 --- a/quickstep/src/com/android/quickstep/recents/data/AppTimersRepositoryImpl.kt +++ b/quickstep/src/com/android/quickstep/recents/data/AppTimersRepositoryImpl.kt @@ -35,7 +35,7 @@ class AppTimersRepositoryImpl( packageName: String, userHandle: UserHandle, ): Duration? = - withContext(dispatcherProvider.background) { + withContext(dispatcherProvider.ioBackground) { val appUsageLimit = dataSource.getAppUsageLimit(packageName, userHandle) ?: return@withContext null diff --git a/quickstep/src/com/android/quickstep/recents/data/TasksRepository.kt b/quickstep/src/com/android/quickstep/recents/data/TasksRepository.kt index 312d4538f1..754707390b 100644 --- a/quickstep/src/com/android/quickstep/recents/data/TasksRepository.kt +++ b/quickstep/src/com/android/quickstep/recents/data/TasksRepository.kt @@ -114,7 +114,7 @@ class TasksRepository( taskRequests[taskId] = Pair( task.key, - recentsCoroutineScope.launch(dispatcherProvider.background) { + recentsCoroutineScope.launch(dispatcherProvider.lightweightBackground) { val thumbnailFetchDeferred = async { fetchThumbnail(task) } val iconFetchDeferred = async { fetchIcon(task) } awaitAll(thumbnailFetchDeferred, iconFetchDeferred) @@ -154,7 +154,7 @@ class TasksRepository( task.key, object : TaskIconChangedCallback { override fun onTaskIconChanged() { - recentsCoroutineScope.launch(dispatcherProvider.background) { + recentsCoroutineScope.launch(dispatcherProvider.lightweightBackground) { updateIcon(task.key.id, getIconFromDataSource(task)) } } @@ -182,7 +182,7 @@ class TasksRepository( (isCurrentThumbnailLowRes && highResEnabled) if (!isRequestedResHigherThanCurrent) return - recentsCoroutineScope.launch(dispatcherProvider.background) { + recentsCoroutineScope.launch(dispatcherProvider.lightweightBackground) { updateThumbnail(task.key.id, getThumbnailFromDataSource(task)) } } @@ -209,10 +209,12 @@ class TasksRepository( } private suspend fun getThumbnailFromDataSource(task: Task) = - withContext(dispatcherProvider.background) { taskThumbnailDataSource.getThumbnail(task) } + withContext(dispatcherProvider.lightweightBackground) { + taskThumbnailDataSource.getThumbnail(task) + } private suspend fun getIconFromDataSource(task: Task) = - withContext(dispatcherProvider.background) { + withContext(dispatcherProvider.lightweightBackground) { val iconCacheEntry = taskIconDataSource.getIcon(task) IconData(iconCacheEntry.icon, iconCacheEntry.contentDescription, iconCacheEntry.title) } diff --git a/quickstep/src/com/android/quickstep/recents/ui/viewmodel/TaskViewModel.kt b/quickstep/src/com/android/quickstep/recents/ui/viewmodel/TaskViewModel.kt index 9236f543d8..15727822f7 100644 --- a/quickstep/src/com/android/quickstep/recents/ui/viewmodel/TaskViewModel.kt +++ b/quickstep/src/com/android/quickstep/recents/ui/viewmodel/TaskViewModel.kt @@ -55,7 +55,7 @@ class TaskViewModel( private val getThumbnailPositionUseCase: GetThumbnailPositionUseCase, dispatcherProvider: DispatcherProvider, ) { - private var taskIds = MutableStateFlow(emptySet()) + private val taskIds = MutableStateFlow(emptySet()) private val isLiveTile = combine( @@ -107,7 +107,7 @@ class TaskViewModel( 0 } } - .flowOn(dispatcherProvider.background) + .flowOn(dispatcherProvider.lightweightBackground) fun bind(vararg taskId: TaskId) { taskIds.value = taskId.toSet().also { Log.d(TAG, "bind: $it") } diff --git a/quickstep/src/com/android/quickstep/views/RecentsViewModelHelper.kt b/quickstep/src/com/android/quickstep/views/RecentsViewModelHelper.kt index ff711da70f..d420bc056e 100644 --- a/quickstep/src/com/android/quickstep/views/RecentsViewModelHelper.kt +++ b/quickstep/src/com/android/quickstep/views/RecentsViewModelHelper.kt @@ -21,7 +21,6 @@ import com.android.quickstep.ViewUtils import com.android.quickstep.recents.viewmodel.RecentsViewModel import com.android.systemui.shared.recents.model.ThumbnailData import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancel import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -44,10 +43,10 @@ class RecentsViewModelHelper( // Update recentsViewModel and apply the thumbnailOverride ASAP, before waiting inside // viewAttachedScope. recentsViewModel.setRunningTaskShowScreenshot(true) - recentsCoroutineScope.launch(dispatcherProvider.background) { + recentsCoroutineScope.launch(dispatcherProvider.lightweightBackground) { recentsViewModel.waitForRunningTaskShowScreenshotToUpdate() recentsViewModel.waitForThumbnailsToUpdate(updatedThumbnails) - withContext(Dispatchers.Main.immediate) { + withContext(dispatcherProvider.main) { ViewUtils.postFrameDrawn(taskView, onFinishRunnable) } } diff --git a/quickstep/src/com/android/quickstep/views/TaskView.kt b/quickstep/src/com/android/quickstep/views/TaskView.kt index 21905dbda0..fb2d936c3a 100644 --- a/quickstep/src/com/android/quickstep/views/TaskView.kt +++ b/quickstep/src/com/android/quickstep/views/TaskView.kt @@ -944,7 +944,7 @@ constructor( // onAttach or another moment in the lifecycle. val coroutineJobsToCancel = coroutineJobs.toList() coroutineJobs.clear() - coroutineScope.launch(dispatcherProvider.background) { + coroutineScope.launch(dispatcherProvider.lightweightBackground) { traceSection("TaskView.onDetachedFromWindow.cancellingJobs") { coroutineJobsToCancel.forEach { it.cancel("TaskView detaching from window") diff --git a/src/com/android/launcher3/util/coroutines/DispatcherProvider.kt b/src/com/android/launcher3/util/coroutines/DispatcherProvider.kt index 1f01b07922..b044abc484 100644 --- a/src/com/android/launcher3/util/coroutines/DispatcherProvider.kt +++ b/src/com/android/launcher3/util/coroutines/DispatcherProvider.kt @@ -16,25 +16,71 @@ package com.android.launcher3.util.coroutines +import com.android.launcher3.Flags.enableCoroutineThreadingImprovements +import com.android.launcher3.util.coroutines.CoroutinesHelper.bgDispatcher +import kotlin.math.max import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.newFixedThreadPoolContext interface DispatcherProvider { + /** + * The default CoroutineDispatcher that is used by all standard builders like launch, async, + * etc. if neither a dispatcher nor any other ContinuationInterceptor is specified in their + * context. + * + * See Kotlin documentation for [Dispatchers.Default] for more detailed documentation. + */ val default: CoroutineDispatcher - val background: CoroutineDispatcher + + /** + * Background thread pool for longer running work e.g. accessing storage, making network + * requests, running AI tasks etc. + */ + val ioBackground: CoroutineDispatcher + + /** + * Background thread pool for UI related work e.g. manipulating in-memory objects for + * presentation on the UI. + */ + val lightweightBackground: CoroutineDispatcher + + /** + * A coroutine dispatcher that is confined to the Main thread operating with UI objects. It + * executes coroutines immediately when it is already in the right context without an additional + * re-dispatch. + * + * See Kotlin documentation for [Dispatchers.Main.immediate] for more detailed documentation. + */ val main: CoroutineDispatcher + + /** + * A coroutine dispatcher that is not confined to any specific thread. + * + * See Kotlin documentation for [Dispatchers.Unconfined] for more detailed documentation. + */ val unconfined: CoroutineDispatcher } object ProductionDispatchers : DispatcherProvider { - private val bgDispatcher = CoroutinesHelper.bgDispatcher() + private val availableProcessors = Runtime.getRuntime().availableProcessors() + private val singleBgThreadPool by lazy { bgDispatcher(availableProcessors, "LauncherBg") } - override val default: CoroutineDispatcher = Dispatchers.Default - override val background: CoroutineDispatcher = bgDispatcher - override val main: CoroutineDispatcher = Dispatchers.Main.immediate - override val unconfined: CoroutineDispatcher = Dispatchers.Unconfined + override val default = Dispatchers.Default + override val main = Dispatchers.Main.immediate + + override val ioBackground = + if (enableCoroutineThreadingImprovements()) + bgDispatcher(nThreads = max(1, availableProcessors / 8), threadName = "LauncherBgIO") + else singleBgThreadPool + + override val lightweightBackground = + if (enableCoroutineThreadingImprovements()) + bgDispatcher(nThreads = max(1, availableProcessors / 8), threadName = "LauncherBgLight") + else singleBgThreadPool + + override val unconfined = Dispatchers.Unconfined } private object CoroutinesHelper { @@ -46,15 +92,12 @@ private object CoroutinesHelper { * contention between then, eventually causing jank. */ @OptIn(DelicateCoroutinesApi::class) - fun bgDispatcher(): CoroutineDispatcher { + fun bgDispatcher(nThreads: Int, threadName: String): CoroutineDispatcher { // Why a new ThreadPool instead of just using Dispatchers.IO with // CoroutineDispatcher.limitedParallelism? Because, if we were to use Dispatchers.IO, we // would share those threads with other dependencies using Dispatchers.IO. // Using a dedicated thread pool we have guarantees only Launcher is able to schedule // code on those. - return newFixedThreadPoolContext( - nThreads = Runtime.getRuntime().availableProcessors(), - name = "LauncherBg", - ) + return newFixedThreadPoolContext(nThreads = nThreads, name = threadName) } } diff --git a/tests/multivalentTests/src/com/android/launcher3/util/TestDispatcherProvider.kt b/tests/multivalentTests/src/com/android/launcher3/util/TestDispatcherProvider.kt index 3319c53c60..76ef8d43fd 100644 --- a/tests/multivalentTests/src/com/android/launcher3/util/TestDispatcherProvider.kt +++ b/tests/multivalentTests/src/com/android/launcher3/util/TestDispatcherProvider.kt @@ -21,7 +21,8 @@ import kotlinx.coroutines.CoroutineDispatcher class TestDispatcherProvider(testDispatcher: CoroutineDispatcher) : DispatcherProvider { override val default: CoroutineDispatcher = testDispatcher - override val background: CoroutineDispatcher = testDispatcher + override val ioBackground: CoroutineDispatcher = testDispatcher + override val lightweightBackground: CoroutineDispatcher = testDispatcher override val main: CoroutineDispatcher = testDispatcher override val unconfined: CoroutineDispatcher = testDispatcher }