https://kotlinlang.org logo
Title
c

ctierney

01/24/2019, 3:36 PM
Question about the kotlinconf-app sample: The
Database
class is full of suspending functions (e.g. https://github.com/JetBrains/kotlinconf-app/blob/master/backend/src/org/jetbrains/kotlinconf/backend/database.kt#L42) that use a dedicated fixed threadpool context. I was wondering what the benefit of this style is? I would understand if the rest of the app called these functions using
async
or something, but as they are all just called synchronously I’m wondering if writing them as suspending functions does anything particular. (Also, as they are not called asynchronously---how does that fixed thread pool actually get used?)
b

bdawg.io

01/24/2019, 4:07 PM
Let's say your application needed to insert a row and cannot do anything else until it does so. What would be the benefit of launching an
async
coroutine just to immediately
await()
on it? By using a suspending function, you are fulfilling a core design of coroutines that "concurrency must be explicit".
async
is only useful if you want to run multiple concurrent operations. Using the fixed thread dispatcher puts a limit on the number of parallel queries executed on the database and by making the methods suspending via
withContext
, you can have more queries queue up for a turn than you have threads (workers that don't get a thread immediately will suspend until one becomes available)
c

ctierney

01/24/2019, 5:15 PM
so when the suspending function is called, control gets handed to the new fixed thread dispatcher even though the calls are not async?
(Definitely agree on the value of keeping concurrency explicit, I just wasn’t sure what else (aside from asynchronicity) using suspending functions enabled.)
b

bdawg.io

01/24/2019, 5:29 PM
@ctierney that is correct. It’s very popular to use a separate pool of threads to perform blocking network/disk calls. So by using a separate fixed thread pool context, it allows your worker threads to be non-blocking and defer the blocking calls to specially allocated threads
c

ctierney

01/24/2019, 5:34 PM
Thank you!