3 ms·
Conclusion: A thread pool is the preferred solution and the go to that I have been using for years. The tricky part is optimizing the size of the pool.
by jqpabc123 3y ago
Conclusion: A thread pool is the preferred solution and the go to that I have been using for years. The tricky part is optimizing the size of the pool.
- sgammon 3y agoI'm not sure a cached pool of OS threads is comparable in this way to coroutines. The author also isn't doing any I/O bound work... or... any work at all? You can schedule coroutines over a threadpool. From the author's code, I'm not even sure this was accounted for in the benchmark. If they are using a threadpool and vanilla coroutines, without specifying where they are scheduled, yes, of course it won't start up a pool of threads for you and be as fast as a pool of threads. It would be terrible if it did that by default.
- tadfisher 3y agoIt does do this by default; Dispatchers.Default wraps a ThreadPoolExecutor with n threads, where n is the number of logical CPU cores. This is used for computation-bound work. The other built-in Dispatcher instances are Dispatchers.IO, with an unbounded thread pool for I/O-bound work; and Dispatchers.Main, which schedules on your platform's UI thread.
- jillesvangurp 3y agoThe IO dispatcher is a fixed size threadpool of 64 threads or the number of cpu cores (whichever is larger). You can use the kotlinx.coroutines.io.parallelism system property to override the default of 64.
- sgammon 3y agoThat would require `withContext(Dispatchers.IO)`...
- sgammon 3y agoIs this the default on all platforms, Android, or JVM?
- hota_mazi 3y agoThat's really not the conclusion, and not something you should seriously do. The rule of thumb should be: - Is your task CPU bound? Put it in a thread pool. - Is your task spending most of its time waiting (e.g. network call)? Use a coroutine
- manmal 3y agoCoroutines also run on a thread pool, and usually the pool size is optimized for the device‘s CPU.
- jillesvangurp 3y agoYou can schedule co-routines on a thread pool. Any Threadpool can be trivially turned into a co-routines dispatcher. Including project loom backed ones (not available on Android of course). The comparison is nonsensical. It's not an either or kind of thing. If your co-routines are doing any blocking IO, you'd use the built in IO dispatcher, which is backed by a thread pool or you'd create your own dispatcher. Each co-routine gets its own thread if you use that; which can then do blocking IO and block the thread. Very common on the jvm if you are interacting with blocking IO things. I was working on some code that needed this yesterday. The examples in this "benchmark" don't make any sense. It's not clear what the work is or why threads/co-routines are even needed. Handling UI events with threads is not a thing. But co-routines are very useful for that. Because they have very low overhead.