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

basher

02/20/2019, 2:54 AM
I want to create a Dispatcher that limits concurrency to 1, but I don’t want the expense of creating a new thread dispatcher. Is there a way to create a limited concurrency dispatcher from the Default dispatcher?
g

gildor

02/20/2019, 2:58 AM
There is no way (no API) for now to create a new dispatchere that reuses threads from IO or Default thread pool, only create a new thread pool and convert it to dispatcher
What is your use case for this?
b

basher

02/20/2019, 3:08 AM
Maybe this isn’t the right thing, so any advice would be appreciated! I have a resource I want to access from a coroutine, but I want to make sure I don’t interact with that resource from more than one coroutine at a time. I realize I’m describing a lock, but I don’t think that’s the right primitive in coroutines. Thoughts?
g

gildor

02/20/2019, 3:10 AM
Also Actor looks as good way to solve this, but Actors API will change, but for such simple case I think it’s fine to use it
Particular implementation depends on how your code should interact with this resource
And I think that 1 threaded Dispatcher is a bad solution for this use case or probably not a solution in general (it will work only access to resource is blocking)
b

basher

02/20/2019, 3:24 AM
Noted! Mutex seems like a good solution for part of what I’m doing. Thanks! I may come back tomorrow with some sample code, after I think so more about the other part. Thanks again!
👍 2
h

hmole

02/20/2019, 9:29 AM
@basher Curious what's your use-case. DB transactions?
p

Paul Woitaschek

02/20/2019, 2:55 PM
You can do Executors.newSingleThread...().asDispatcher() or sth alike
b

basher

02/20/2019, 3:32 PM
talking about about db transactions yes, but i've recently realized it's moot
SQLDelight mostly takes care of this
g

gildor

02/20/2019, 4:42 PM
You can do Executors.newSingleThread...().asDispatcher() or sth alike
It's true, but in most cases it's just not needed Also it easy to leak thread (such exector should be explicitly closed to solve problem of leaked thread) Also it will not work with non-blocking APIs
👏 2
7 Views