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
| // ❌ 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) { |
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
| // ❌ 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) { |
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
| 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() | |
| } | |
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 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 |
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 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}") |
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() |
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 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) { |
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 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, |
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
| 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() | |
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
| 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) { |
NewerOlder