https://kotlinlang.org logo
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
benchmarks
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
confetti
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
lincheck
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by
Title
m

mp

02/12/2019, 2:02 PM
Is there a coroutine-flavored equivalent of a j.u.c.semaphore? I have a known amount of work to send over the network, and it can only be handled of batches of at most 10, so I’d like to simply spawn a zillion coroutines, each of which will handle 10 items, but to avoid overwhelming the other end I’d like to limit the concurrency ala a semaphore.
a

antonis

02/12/2019, 2:10 PM
I guess you can use Channels and/or Actors for that
I don’t think there is something as low level as semaphores
m

mp

02/12/2019, 2:12 PM
That’s unfortunate.
m

marstran

02/12/2019, 2:22 PM
Fanning in to a channel with a set amount of workers reading from it, is a better abstraction than a semaphore imho.
💯 4
m

mp

02/12/2019, 2:29 PM
Fan-in via a channel makes it harder to keep track of the result of each unit of work, though.
I can’t simply keep a collection of Deferreds or whatever
a

antonis

02/12/2019, 2:32 PM
Semaphores are hard imho or at least for most of us 😛
m

mp

02/12/2019, 2:34 PM
😥
a

antonis

02/12/2019, 2:34 PM
You can still use java semaphore. That’s the beauty of Kotlin
m

mp

02/12/2019, 2:35 PM
I can, but that will tie up the whole thread, no?
a

antonis

02/12/2019, 2:35 PM
yes
m

mp

02/12/2019, 2:35 PM
That defeats the purpose…
I want to spawn a few thousand coroutines, not a few thousand threads
a

antonis

02/12/2019, 2:40 PM
probably you can imitate semaphore behavior by having a block locked with Mutex https://kotlinlang.org/docs/reference/coroutines/shared-mutable-state-and-concurrency.html#mutual-exclusion
I feel that channels/actors is the way to go in a kotlin world though
m

mp

02/12/2019, 2:47 PM
OK but you see that they’re not equivalent, right…
b

bdawg.io

02/12/2019, 2:54 PM
Immediately inside of your batch worker, you could use an object pool of Mutex and try to obtain the a suspending lock which will create a suspending queue of workers waiting their turn
👍 1
m

marstran

02/12/2019, 2:58 PM
Answering: "Fan-in via a channel makes it harder to keep track of the result of each unit of work, though." You could send a response channel with the request. The caller could then just suspend by calling
receive
on response channel.
b

bdawg.io

02/12/2019, 2:59 PM
If you will only have a single response that you need to know of, a
CompletableDeferred
is cheaper than a channel is.
m

marstran

02/12/2019, 3:00 PM
Yeah, right, that is better 👍
m

mp

02/12/2019, 3:09 PM
I have thousands of responses to keep track of
I agree that response channel per request, mutex pool, etc, can work. However, I don’t want a coworker who opens this project to come away scarred for life thinking that concurrency has to be that complicated 😕
b

bdawg.io

02/12/2019, 3:21 PM
It’s going to be complicated if you’re trying to do things in a difficult way. IMO the better thing would be to only launch the number of coroutines that you want to happen concurrently and then fan out the work using a channel. https://kotlinlang.org/docs/reference/coroutines/channels.html#fan-out
data class WorkItem(val value: String, val response: CompletableDeferred<Response> = CompletableDeferred())

val workValues: ReceiveChannel<WorkValue> = getValues()
coroutineScope {
    repeat(workerCount) {
        launch {
            doSomething(workValues.receiveNextTen())
        }
    }
}
1
m

mp

02/12/2019, 3:23 PM
“a difficult way” — the way that semaphores make really simple 😕
b

bdawg.io

02/12/2019, 3:29 PM
How is a semaphore simpler than a MutexPool? Also, semaphores are also blocking 🤷. Semaphore tracks access by the thread. MutexPool tracks access by suspension.
m

mp

02/12/2019, 3:35 PM
See the start of this thread. I’m looking for a suspending equivalent to a semaphore
b

bdawg.io

02/12/2019, 3:36 PM
Right, which is why I suggested a MutexPool (and even gave an implementation) 🙂
m

mp

02/12/2019, 3:38 PM
Merely lamenting the lack of a simpler choice.
b

bdawg.io

02/12/2019, 3:47 PM
val semaphore = Semaphore(10)

repeat(20) {
    thread {
        // blocking
        semaphore.aquire()
        try {
            doSomething()
        } finally {
            semaphore.release()
        }
    }
}
vs
val mutexPool = MutexPool(10)

repeat(20) {
    launch {
        // suspending
        mutexPool.withLock {
            doSomething()
        }
    }
}
I’m just trying to understand what “simpler” means
m

mp

02/12/2019, 4:22 PM
Well, one of them requires having a roll-your-own concurrency building block, and one does not.
That means that a less experienced developer can’t look at this code and see a pattern they can use easily somewhere else.
m

marstran

02/12/2019, 4:35 PM
Using fan-in on a channel is a common pattern and really straight forward to implement. I really don't get what you think is complicated with it.
m

mp

02/12/2019, 5:07 PM
I didn’t say fan-in was complicated. I said that fan-in plus enough other machinery to do what semaphores do is complicated. If you disagree, okay. 🤷‍♂️
b

bdawg.io

02/12/2019, 7:12 PM
So the issue is because Semaphore is part of the JDK whereas a MutexPool is not part of coroutines core? (event though it’s a 20 line wrapper, including whitespace, around
Mutex
and
select
from the core library). I would still argue that it sounds like the design causing the need for a semaphore has an alternative that’s simpler and cleaner in coroutines, but I’m not that close to the original problem to say more. The nice part is coroutines being open source makes it nice to open (or implement) feature requests. (Most of which either get implemented fairly quick or get rejected with a real reason)
👏 1
2