Skip to content

Instantly share code, notes, and snippets.

// ❌ Wrong: CPU-intensive work on IO dispatcher
suspend fun processData(data: List<Int>) = withContext(Dispatchers.IO) {
data.map { it * it * it * it } // CPU-intensive
}
// ✅ Correct: CPU-intensive work on Default dispatcher
suspend fun processData(data: List<Int>) = withContext(Dispatchers.Default) {
data.map { it * it * it * it }
}
// ❌ Wrong: Network call on Default dispatcher
suspend fun fetchData() = withContext(Dispatchers.Default) {
// ❌ Wrong: Blocking call without withContext
suspend fun badExample() {
Thread.sleep(1000) // Blocks the thread!
}
// ✅ Correct: Use delay for coroutines
suspend fun goodExample() {
delay(1000) // Suspends without blocking
}
// ✅ Correct: Use withContext for blocking calls
suspend fun blockingOperation() = withContext(Dispatchers.IO) {
class DataProcessor {
suspend fun processAllData(items: List<String>): List<String> = coroutineScope {
// All child coroutines will complete before returning
items.map { item ->
async(Dispatchers.Default) {
processItem(item)
}
}.awaitAll()
}
import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis
suspend fun performanceTest() {
val data = List(1000) { it }
// Sequential processing
val sequentialTime = measureTimeMillis {
data.forEach { item ->
delay(10)
// process item
import kotlinx.coroutines.*
import java.util.concurrent.Executors
class DatabaseService {
// Custom dispatcher with limited threads matching DB connection pool
private val dbDispatcher = Executors.newFixedThreadPool(5).asCoroutineDispatcher()
data class QueryResult(val data: List<String>)
suspend fun executeQuery(query: String): QueryResult = withContext(dbDispatcher) {
println("Executing '$query' on ${Thread.currentThread().name}")
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()
import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
import kotlin.system.measureTimeMillis
class RateLimitedApiClient {
private val maxConcurrentRequests = 10
private val semaphore = Semaphore(maxConcurrentRequests)
suspend fun makeApiCall(id: Int): String = semaphore.withPermit {
withContext(Dispatchers.IO) {
import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis
data class ScrapedData(val url: String, val title: String, val contentLength: Int)
class WebScraper {
suspend fun scrapeWebsite(url: String): ScrapedData = withContext(Dispatchers.IO) {
println("Scraping $url on ${Thread.currentThread().name}")
delay(500) // Simulate network request
ScrapedData(
url = url,
class EventProcessor {
suspend fun processEvent(event: String) = withContext(Dispatchers.Unconfined) {
// Use unconfined for immediate processing without thread switching overhead
// Only suitable when no specific thread is required
println("Processing $event immediately on ${Thread.currentThread().name}")
}
}
fun main() = runBlocking {
val processor = EventProcessor()
fun main() = runBlocking {
println("Main thread: ${Thread.currentThread().name}")
launch(Dispatchers.Unconfined) {
println("1. Unconfined - Start: ${Thread.currentThread().name}")
delay(100)
println("2. Unconfined - After delay: ${Thread.currentThread().name}")
withContext(Dispatchers.Default) {