https://kotlinlang.org logo
#coroutines
Title
# coroutines
b

Byron Katz

03/28/2021, 9:19 PM
I've been holding off from coroutines a while now. Every time I tried adding them, I'd run into severe headwinds. Today I tried again, and basically just converted my executor service like this:
Copy code
-    executorService: ExecutorService = Executors.newCachedThreadPool(Executors.defaultThreadFactory())
+    executorService: ExecutorService = Executors.newCachedThreadPool(Executors.defaultThreadFactory()).asCoroutineDispatcher().executor as ExecutorService,
and bam! Performance up by 40% on my heaviest function.
e

elizarov

03/29/2021, 6:16 AM
Very strange. It should not be making a difference. Double-check your benchmarks.
b

Byron Katz

03/29/2021, 1:37 PM
The man himself! But why shouldn't that make a difference?
e

elizarov

03/29/2021, 1:41 PM
Copy code
val originalExecutor = Executors.newCachedThreadPool(Executors.defaultThreadFactory())
val resultingExecutor = originalExecutor.asCoroutineDispatcher().executor as ExecutorService
println(resultingExecutor === originalExecutor) // prints true
b

Byron Katz

03/29/2021, 1:42 PM
aww
I should have looked closer. So, what is the proper way to convert an executor service to a coroutine version?
e

elizarov

03/29/2021, 1:43 PM
It is the proper way. What are you trying to achieve?
b

Byron Katz

03/29/2021, 1:44 PM
Trying to use the exact same interface that ExecutorService provides for threads, but for coroutines, i.e.
foo.submit ()
e

elizarov

03/29/2021, 1:44 PM
For what?
b

Byron Katz

03/29/2021, 1:46 PM
for a non-ssl server, an ssl-server, a blockingLinkedQueue, and for handling client requests. I pass one ExecutorService around the entire application to be used. Currently it works fine with a cached pool of threads but I was hoping to just sprinkle some magic coroutines in to avoid the 1-1 dependency on OS threads.
e

elizarov

03/29/2021, 1:47 PM
It does not work this way. There is no magic
b

Byron Katz

03/29/2021, 1:47 PM
😢
I guess I was hoping there was a way to incorporate coroutines without a total overhaul of the codebase, and to date I haven't found a way to do this.
4 Views