Created
October 4, 2025 03:07
-
-
Save anandwana001/aff4984b5992ccce943fd2b3e0f77cbf to your computer and use it in GitHub Desktop.
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
| import java.util.concurrent.Executors | |
| class CustomDispatchers { | |
| // Single-threaded dispatcher for sequential processing | |
| val singleThread = Executors.newSingleThreadExecutor().asCoroutineDispatcher() | |
| // Fixed thread pool | |
| val fixedThreadPool = Executors.newFixedThreadPool(4).asCoroutineDispatcher() | |
| // Cached thread pool (creates threads as needed) | |
| val cachedThreadPool = Executors.newCachedThreadPool().asCoroutineDispatcher() | |
| fun close() { | |
| singleThread.close() | |
| fixedThreadPool.close() | |
| cachedThreadPool.close() | |
| } | |
| } | |
| fun main() = runBlocking { | |
| val dispatchers = CustomDispatchers() | |
| try { | |
| // Use single-threaded dispatcher for order-sensitive operations | |
| withContext(dispatchers.singleThread) { | |
| repeat(5) { i -> | |
| launch { | |
| println("Task $i on ${Thread.currentThread().name}") | |
| delay(100) | |
| } | |
| } | |
| } | |
| delay(1000) | |
| } finally { | |
| dispatchers.close() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment