-
Notifications
You must be signed in to change notification settings - Fork 377
chore: Dispatcher Threads #2375
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
28 commits
Select commit
Hold shift + click to select a range
69be316
Using dispatcher
1843ebe
Update threads to 2
15020a9
Updated methods
0424159
linting
4ad5636
readme
6739f9d
using the same thread pool
31aba06
lint
dedb996
making sure initstate has the right value
924c088
lint
272640b
Clear state and skip performance tests
7302b53
lint
a996b7b
clear preferences
1c367a9
fixing tests
89df7a2
fixing tests
6750b9d
fixing tests
312f4a1
fixing tests
b6d44b8
fixing tests
5b6cf2a
addressed PR comments
3736b91
Addressed comments and fixed tests
06fde5d
lint
bea28d2
lint
3bb3963
fix test
1aa5de6
lint
843c884
rewrote the test
96101bf
fix test
c0ef843
made the test more robust
3462ea1
clear all preferences and simplified mocks
581610f
added more robustness
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
21 changes: 0 additions & 21 deletions
21
...DK/onesignal/core/src/main/java/com/onesignal/common/threading/OSPrimaryCoroutineScope.kt
This file was deleted.
Oops, something went wrong.
186 changes: 186 additions & 0 deletions
186
...alSDK/onesignal/core/src/main/java/com/onesignal/common/threading/OneSignalDispatchers.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,186 @@ | ||
| package com.onesignal.common.threading | ||
|
|
||
| import com.onesignal.debug.internal.logging.Logging | ||
| import kotlinx.coroutines.CoroutineDispatcher | ||
| import kotlinx.coroutines.CoroutineScope | ||
| import kotlinx.coroutines.Dispatchers | ||
| import kotlinx.coroutines.SupervisorJob | ||
| import kotlinx.coroutines.asCoroutineDispatcher | ||
| import kotlinx.coroutines.isActive | ||
| import kotlinx.coroutines.launch | ||
| import java.util.concurrent.LinkedBlockingQueue | ||
| import java.util.concurrent.ThreadFactory | ||
| import java.util.concurrent.ThreadPoolExecutor | ||
| import java.util.concurrent.TimeUnit | ||
| import java.util.concurrent.atomic.AtomicInteger | ||
|
|
||
| /** | ||
| * Optimized threading manager for the OneSignal SDK. | ||
| * | ||
| * Performance optimizations: | ||
| * - Lazy initialization to reduce startup overhead | ||
| * - Custom thread pools for both IO and Default operations | ||
| * - Optimized thread pool configuration (smaller pools) | ||
| * - Small bounded queues (10 tasks) to prevent memory bloat | ||
| * - Reduced context switching overhead | ||
| * - Efficient thread management with controlled resource usage | ||
| */ | ||
| internal object OneSignalDispatchers { | ||
| // Optimized pool sizes based on CPU cores and workload analysis | ||
| private const val IO_CORE_POOL_SIZE = 2 // Increased for better concurrency | ||
| private const val IO_MAX_POOL_SIZE = 3 // Increased for better concurrency | ||
| private const val DEFAULT_CORE_POOL_SIZE = 2 // Optimal for CPU operations | ||
| private const val DEFAULT_MAX_POOL_SIZE = 3 // Slightly larger for CPU operations | ||
| private const val KEEP_ALIVE_TIME_SECONDS = | ||
| 30L // Keep threads alive longer to reduce recreation | ||
| private const val QUEUE_CAPACITY = | ||
| 10 // Small queue that allows up to 10 tasks to wait in queue when all threads are busy | ||
| internal const val BASE_THREAD_NAME = "OneSignal" // Base thread name prefix | ||
| private const val IO_THREAD_NAME_PREFIX = | ||
| "$BASE_THREAD_NAME-IO" // Thread name prefix for I/O operations | ||
| private const val DEFAULT_THREAD_NAME_PREFIX = | ||
| "$BASE_THREAD_NAME-Default" // Thread name prefix for CPU operations | ||
|
|
||
| private class OptimizedThreadFactory( | ||
| private val namePrefix: String, | ||
| private val priority: Int = Thread.NORM_PRIORITY, | ||
| ) : ThreadFactory { | ||
| private val threadNumber = AtomicInteger(1) | ||
|
|
||
| override fun newThread(r: Runnable): Thread { | ||
| val thread = Thread(r, "$namePrefix-${threadNumber.getAndIncrement()}") | ||
| thread.isDaemon = true | ||
| thread.priority = priority | ||
| return thread | ||
| } | ||
| } | ||
|
|
||
| private val ioExecutor: ThreadPoolExecutor by lazy { | ||
| try { | ||
| ThreadPoolExecutor( | ||
| IO_CORE_POOL_SIZE, | ||
| IO_MAX_POOL_SIZE, | ||
| KEEP_ALIVE_TIME_SECONDS, | ||
| TimeUnit.SECONDS, | ||
| LinkedBlockingQueue(QUEUE_CAPACITY), | ||
| OptimizedThreadFactory( | ||
| namePrefix = IO_THREAD_NAME_PREFIX, | ||
| priority = Thread.NORM_PRIORITY - 1, | ||
| // Slightly lower priority for I/O tasks | ||
| ), | ||
| ).apply { | ||
| allowCoreThreadTimeOut(false) // Keep core threads alive | ||
| } | ||
| } catch (e: Exception) { | ||
| Logging.error("OneSignalDispatchers: Failed to create IO executor: ${e.message}") | ||
| throw e // Let the dispatcher fallback handle this | ||
| } | ||
| } | ||
|
|
||
| private val defaultExecutor: ThreadPoolExecutor by lazy { | ||
| try { | ||
| ThreadPoolExecutor( | ||
| DEFAULT_CORE_POOL_SIZE, | ||
| DEFAULT_MAX_POOL_SIZE, | ||
| KEEP_ALIVE_TIME_SECONDS, | ||
| TimeUnit.SECONDS, | ||
| LinkedBlockingQueue(QUEUE_CAPACITY), | ||
| OptimizedThreadFactory(DEFAULT_THREAD_NAME_PREFIX), | ||
| ).apply { | ||
| allowCoreThreadTimeOut(false) // Keep core threads alive | ||
| } | ||
| } catch (e: Exception) { | ||
| Logging.error("OneSignalDispatchers: Failed to create Default executor: ${e.message}") | ||
| throw e // Let the dispatcher fallback handle this | ||
| } | ||
| } | ||
|
|
||
| // Dispatchers and scopes - also lazy initialized | ||
| val IO: CoroutineDispatcher by lazy { | ||
| try { | ||
| ioExecutor.asCoroutineDispatcher() | ||
| } catch (e: Exception) { | ||
| Logging.error("OneSignalDispatchers: Using fallback Dispatchers.IO dispatcher: ${e.message}") | ||
| Dispatchers.IO | ||
| } | ||
| } | ||
|
|
||
| val Default: CoroutineDispatcher by lazy { | ||
| try { | ||
| defaultExecutor.asCoroutineDispatcher() | ||
| } catch (e: Exception) { | ||
| Logging.error("OneSignalDispatchers: Using fallback Dispatchers.Default dispatcher: ${e.message}") | ||
| Dispatchers.Default | ||
| } | ||
| } | ||
|
|
||
| private val IOScope: CoroutineScope by lazy { | ||
| CoroutineScope(SupervisorJob() + IO) | ||
| } | ||
|
|
||
| private val DefaultScope: CoroutineScope by lazy { | ||
| CoroutineScope(SupervisorJob() + Default) | ||
| } | ||
|
jkasten2 marked this conversation as resolved.
|
||
|
|
||
| fun launchOnIO(block: suspend () -> Unit) { | ||
| IOScope.launch { block() } | ||
| } | ||
|
|
||
| fun launchOnDefault(block: suspend () -> Unit) { | ||
| DefaultScope.launch { block() } | ||
| } | ||
|
|
||
| internal fun getPerformanceMetrics(): String { | ||
| return try { | ||
| """ | ||
| OneSignalDispatchers Performance Metrics: | ||
| - IO Pool: ${ioExecutor.activeCount}/${ioExecutor.corePoolSize} active/core threads | ||
| - IO Queue: ${ioExecutor.queue.size} pending tasks | ||
| - Default Pool: ${defaultExecutor.activeCount}/${defaultExecutor.corePoolSize} active/core threads | ||
| - Default Queue: ${defaultExecutor.queue.size} pending tasks | ||
| - Total completed tasks: ${ioExecutor.completedTaskCount + defaultExecutor.completedTaskCount} | ||
| - Memory usage: ~${(ioExecutor.activeCount + defaultExecutor.activeCount) * 1024}KB (thread stacks, ~1MB each) | ||
| """.trimIndent() | ||
| } catch (e: Exception) { | ||
| "OneSignalDispatchers not initialized or using fallback dispatchers ${e.message}" | ||
| } | ||
| } | ||
|
|
||
| internal fun getStatus(): String { | ||
| val ioExecutorStatus = | ||
| try { | ||
| if (ioExecutor.isShutdown) "Shutdown" else "Active" | ||
| } catch (e: Exception) { | ||
| "ioExecutor Not initialized ${e.message ?: "Unknown error"}" | ||
| } | ||
|
|
||
| val defaultExecutorStatus = | ||
| try { | ||
| if (defaultExecutor.isShutdown) "Shutdown" else "Active" | ||
| } catch (e: Exception) { | ||
| "defaultExecutor Not initialized ${e.message ?: "Unknown error"}" | ||
| } | ||
|
|
||
| val ioScopeStatus = | ||
| try { | ||
| if (IOScope.isActive) "Active" else "Cancelled" | ||
| } catch (e: Exception) { | ||
| "IOScope Not initialized ${e.message ?: "Unknown error"}" | ||
| } | ||
|
|
||
| val defaultScopeStatus = | ||
| try { | ||
| if (DefaultScope.isActive) "Active" else "Cancelled" | ||
| } catch (e: Exception) { | ||
| "DefaultScope Not initialized ${e.message ?: "Unknown error"}" | ||
| } | ||
|
|
||
| return """ | ||
| OneSignalDispatchers Status: | ||
| - IO Executor: $ioExecutorStatus | ||
| - Default Executor: $defaultExecutorStatus | ||
| - IO Scope: $ioScopeStatus | ||
| - Default Scope: $defaultScopeStatus | ||
| """.trimIndent() | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't think we should try-catch here:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ok i will merge this into the refactor branch and fix it there. thanks