Skip to content

Instantly share code, notes, and snippets.

@anandwana001
Created October 4, 2025 03:07
Show Gist options
  • Select an option

  • Save anandwana001/aff4984b5992ccce943fd2b3e0f77cbf to your computer and use it in GitHub Desktop.

Select an option

Save anandwana001/aff4984b5992ccce943fd2b3e0f77cbf to your computer and use it in GitHub Desktop.
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