https://kotlinlang.org logo
Docs
Join the conversationJoin Slack
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
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
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
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 Linen
coroutines
  • g

    groostav

    08/07/2018, 12:12 AM
    Hey gents, does anybody have a good blog post or guide on using
    kotlinx.coroutines.experimental.internal.LockFreeLinkedListHead
    and friends? I'm using
    AtomicReference
    with immutable classes and its working, but at this point I'm now asking my
    getAndUpdate
    call to allocate a lot of new data in its `update`er method. some notes: - yes I know that class isnt formally part of the API, I will update as appropriate, and either copy-paste that code or keep everything at version zero. - my existing solution probably would be fine if
    kotlinx.collections.immutable
    was part of the stdlib, or I wanted to include it as an external dep, but its not, and I don't, and it seems to have lost all steam, much to my shigrin - no, I dont want to use
    atomicfu
    because I dont understand what atomicfu is asking me to do to my build system, ill poke around at gradle + byte code manipulation later.
    e
    a
    • 3
    • 2
  • v

    v0ldem0rt

    08/07/2018, 12:35 AM
    Is there any overhead of multiple coroutines waiting on same Deferred<T> (race conditions/thread safety)?
    p
    g
    +2
    • 5
    • 8
  • b

    bdawg.io

    08/07/2018, 7:17 PM
    Does anyone know of any Async JDBC-esque DataSource implementations that aren’t just delegating to a separate thread to block on?
    c
    w
    +2
    • 5
    • 6
  • b

    bdawg.io

    08/07/2018, 7:31 PM
    And if not, if I wanted to have a coroutine context for database access, is the current practice to have an
    N
    thread coroutine context with a
    N
    sized pooled data source?
    g
    • 2
    • 1
  • p

    pavel

    08/07/2018, 9:26 PM
    That is the default behaviour of
    close()
    as I am reading the docs https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-send-channel/close.html
    🤔 1
    g
    • 2
    • 1
  • g

    groostav

    08/09/2018, 9:41 AM
    So the first thing that might help here is using the
    Unconfined
    dispatcher in your
    map
    function, I think this will get your outer deferred running on the inner deferred's thread, which might make this a bit more straight forward to debug
    n
    • 2
    • 1
  • u

    uli

    08/09/2018, 12:54 PM
    @groostav await should preserve the happens before semantic. Everything happening inside the async should be visible to everything happening after the async But I would also guess for some threading issue. @nayanjyoti is your
    a
    shared somewhere else, where it could be reset to null?
    n
    • 2
    • 2
  • g

    groostav

    08/09/2018, 6:51 PM
    Everything happening inside the async should be visible to everything happening after the async
    My reading of java concurrency in practice is that this is not accurate
    j
    • 2
    • 1
  • g

    groostav

    08/09/2018, 6:54 PM
    val notThreadSafe: Int? = null
    
    fun doStuff() = runBlocking {
      val updateJob = launch(CommonPool) { notThreadSafe = 1 }
    
      updateJob.join()
      val result = notThreadSafe // <- no gaurentee this isnt null, in fact theres no gaurentee that your thread will _ever_ see the value `1` on that field.
    }
    this is true despite happens before semantics. the assignment of
    1
    to
    notThreadSafe
    happens before the assignment of
    notThreadSafe
    to
    result
    , but because its not marked as
    @Volatile
    you have no gaurentees about when the value
    notTHreadSafe
    will actually be written to main memory. Your only gaurentee is that all downstream operations on that thread on the common pool will see the value
    1
    for not thread safe. I could be mistaken. Java Concurrency in Practice is a uniquely horrifying book to read.
    e
    g
    • 3
    • 4
  • m

    mp

    08/09/2018, 7:40 PM
    I think it's more that memory models are uniquely horrifying 😉
    g
    e
    • 3
    • 2
  • s

    Seri

    08/09/2018, 7:52 PM
    Does anyone have examples of Channels in use in real projects?
    👍 3
    g
    l
    • 3
    • 2
  • s

    Seri

    08/09/2018, 9:10 PM
    Ah gotcha, I appreciate the response nonetheless.
    g
    c
    • 3
    • 4
  • i

    igorvd

    08/10/2018, 5:18 PM
    What is the best way to achieve some periodic task with coroutines? I'm simply starting a coroutine with launch and using a
    while (isActive)
    with a delay. Is this the best approach?
    v
    w
    • 3
    • 4
  • v

    v0ldem0rt

    08/11/2018, 5:22 AM
    If I want to invoke a suspend fun from Java what is the return type?
    e
    • 2
    • 1
  • p

    Paul Woitaschek

    08/13/2018, 2:16 PM
    https://youtrack.jetbrains.com/issue/KT-26100
    i
    • 2
    • 2
  • e

    elizarov

    08/13/2018, 5:01 PM
    Some Samsung Android 5.x devices do not properly support
    Atomic*FieldUpdater
    Java APIs which leads to crashes with
    kotlinx.coroutines
    . Do you know more details? How shall we work around this problem? You opinion is welcome here: https://github.com/Kotlin/kotlinx.coroutines/issues/490
    t
    • 2
    • 1
  • v

    v0ldem0rt

    08/13/2018, 5:13 PM
    why don't we already have a Semaphore implementation in coroutines?
    m
    e
    l
    • 4
    • 15
  • a

    Albert

    08/14/2018, 12:02 PM
    Is there a way to cap the concurrency with coroutines? when I run a lot of
    async { ... http request ... }
    at some point I am hitting connection refused, because the other end can not keep up.
    v
    • 2
    • 2
  • w

    withoutclass

    08/14/2018, 2:06 PM
    While loop probably, since the for loop will suspend waiting on items as I recall
    m
    • 2
    • 12
  • r

    Ruckus

    08/14/2018, 5:11 PM
    I have a use case that I'm not sure how to solve (my experience with async/concurrent code is rather simplistic). Basically I have two types of tasks: generate tasks and a combine task. I would like generate tasks to run concurrently from a queue (the generate tasks are quite CPU intensive, so I want to limit the number that run at a time). When the queue runs dry, it should then run the combine task. While the combine task is running, new generate tasks can be added to the queue, but should not run till the combine task is done. (By extension, the combine task should not run if there are any generate tasks running.) Also, there will often be long periouds of time where no tasks are running, so I don't want a busy wait for new generate tasks. What would be the correct way to handle this? Is there a common idiom or pattern for such a use case?
    • 1
    • 1
  • b

    bj0

    08/14/2018, 5:16 PM
    you can probably handle the selection of which task to run using a select clause, which bias the first clause (generate tasks) over the second (combine task)
    r
    • 2
    • 26
  • b

    bdawg.io

    08/14/2018, 5:19 PM
    val result = async(myContext) { doSomething() }.await()
    // vs
    val result = withContext(myContext) { doSomething() }
    i
    w
    +4
    • 7
    • 8
  • v

    v0ldem0rt

    08/14/2018, 5:56 PM
    How can I get current Continuation inside a coroutine?
    e
    • 2
    • 1
  • v

    v0ldem0rt

    08/15/2018, 3:25 AM
    When do we think https://github.com/Kotlin/kotlinx.coroutines/pull/455 will be availble GA? I desperately need MDCContext
    v
    • 2
    • 3
  • d

    DALDEI

    08/15/2018, 10:25 PM
    Recomendation for what api/syntax/idiom to use when running in a coroutine or suspendinmg function and calling a known 'blocking' API (e.g. normal java IO blocking apis). Docs say do NOT use runBlocking() -- so ok. what do I use ?
    g
    w
    • 3
    • 4
  • a

    alex.tavella

    08/17/2018, 11:52 AM
    No, right?
    m
    b
    u
    • 4
    • 12
  • t

    tianhao

    08/19/2018, 11:19 PM
    Will coroutines team consider to work with gRPC team?
    g
    v
    v
    • 4
    • 3
  • e

    elizarov

    08/20/2018, 7:39 AM
    @louiscad Coroutines don’t immediately allow recursive methods without StackOverflow, but you can use Kotlin coroutines machinery to transform any recursive algorithm that uses call stack into one that uses heap to maintain its stack, thus supporting much deeper recursion without running out of resources. I wrote a prototype at one point. See this gist: https://gist.github.com/elizarov/d715c9564288c2635bb55687e7341717
    👍 2
    l
    • 2
    • 3
  • l

    louiscad

    08/20/2018, 8:22 AM
    What's the most idiomatic way to listen to multiple channels of different types and run a method with all the latest values each time? I mean, let's say I have
    channelA: Channel<A>
    and
    channelB: Channel<B>
    , I want to call a method like
    update(a: A, b: B)
    each time I get a value from any channel, that is, if I receive from
    channelA
    , I want it to be called with the new
    A
    value, and the same
    B
    value as previously received. Each time I have a use case for it, I feel like I'm writing disposable/throwaway code that is a bit error-prone and quite boilerplate-y. If you have any clue about a solution to do it right once for all, in a kind of generic way, please tell! Bonus points if your solution can also work with other callbacks and not just
    Channel
    g
    j
    +3
    • 6
    • 24
  • a

    aeruhxi

    08/20/2018, 12:18 PM
    when I swap
    launch
    with
    runBlocking
    , everything works though
    u
    • 2
    • 4
Powered by Linen
Title
a

aeruhxi

08/20/2018, 12:18 PM
when I swap
launch
with
runBlocking
, everything works though
u

uli

08/20/2018, 5:20 PM
Could it be that other coroutines are blocking all threads in the CommonPool? How man subscribe() calls do you have launched? If this is the case, runBlocking would borrow one of these threads whils launch would schedule a new coroutine waiting for an executor thread to become idle. Generally, it would be good practice to launch the blocking subscribe() calls in a separate thread pool and not waste the CommonPool.
a

aeruhxi

08/20/2018, 5:42 PM
just one subscribe call.. although that subscribe continuously polls, if that matters. What do you mean by using separate thread pool for it?
u

uli

08/20/2018, 9:03 PM
You can pass a coroutine context to launch, async, etc. The context holds a dispatcher which decides where to schedule coroutines. The default context is the CommonPool which holds CPU-1 threads (or something like that). If you have blocking code in your coroutine, that will tie up one thread until the blocking code terminates. If all threads are tied up, new coroutines will not execute until one of the threads is released due to a coroutine suspending out terminating. You can create contexts with your own dispatchers with methods like newFixedThreadPoolContext.
a

aeruhxi

08/21/2018, 6:18 AM
I tried using separate context. Same problem.
View count: 2