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
f

fitermay

07/27/2022, 8:30 PM
What's the pattern to dispose of a resource when a suspend function needs to allocated a disposable resource. How do I handle the case where the cancellation happens after the resource is allocated but right before it's returned?
j

Joffrey

07/27/2022, 9:25 PM
Cancellation is cooperative in coroutines, it cannot happen in every possible instant. The places where it can happen are predictable. But in any case, cancellation can be handled like any other exception. If you have a resource that needs cleanup, use a
try/finally
block to clean it up in every scenario (normal completion and exceptions)
f

fitermay

07/27/2022, 9:53 PM
It cannot happen when returning from one suspend function to another?
Internally, can't the return happen via continuation so the invoking coroutine can be cancelled?
z

Zach Klippenstein (he/him) [MOD]

07/27/2022, 11:02 PM
It cannot happen when returning from one suspend function to another?
No. For example, if you run this `foo`:
suspend fun foo() {
    val job = coroutineContext.job
    println("In foo, calling bar (isActive=${job.isActive})")
    bar()
    println("In foo, after bar returned (isActive=${job.isActive})")

}

suspend fun bar() {
    println("In bar, cancelling job…")
    coroutineContext.job.cancel()
    println("In bar, job cancelled, returning to foo…")
}
You’ll get this sequence of messages:
In foo, calling bar (isActive=true)
In bar, cancelling job…
In bar, job cancelled, returning to foo…
In foo, after bar returned (isActive=false)
u

uli

07/27/2022, 11:18 PM
The issue can happen in innocent looking code when unsing `withContext`:
suspend fun allocateResource() = withContext(<http://Dispatchers.io|Dispatchers.io>) {
  // allocate resource. E.g. open a database
  return resource
}

suspend fun leakResource() {
  val ressource = allocateResource()
  try {
    doSomething(resource)
  } finally {
    ressource.close()
  }
}
withContext
would catch the cancelation before returning and leak the resource even before it is returned from
allocateRessource
. Nothing much you can do about it.
e

ephemient

07/27/2022, 11:18 PM
relatedly, 1. in a suspend fun with a long chain of blocking calls, you may need
ensureActive()
or
runInterruptible {}
to allow for cancellation in the middle 2. you should not make suspend calls or launch new coroutines in a
finally
(or
catch (Exception)
block if it could contain
CancellationException
) because the containing job may be cancelled which would cause such calls to immediately propagate cancellation instead
Uli, there's
withContext(NonCancellable)
if you need to ensure cancellation doesn't happen in the midst of a certain block
u

uli

07/27/2022, 11:23 PM
@ephemient the issue in above exmaple is after the withContext block terminates. Not sure if withContext(NonCancellable) would skip cancelation checks on exit as well. If anyone is up to test it let us know the results, please.
e

ephemient

07/27/2022, 11:34 PM
you just need something like
var resource: Resource? = null
try {
    withContext(NonCancellable) {
        resource = allocateResource()
    }
    doSomething(resource)
} finally {
    resource?.close()
}
u

uli

07/27/2022, 11:39 PM
Correct. The pitfall is though, that the caller needs to take care of the NonCancellable context. And has to understand the issue enough to put the assignment of resource into the try block
f

fitermay

07/27/2022, 11:43 PM
So I guess the implicit continuations from one suspend to another do not go through a dispatcher
e

ephemient

07/27/2022, 11:49 PM
the caller gets resumed (with exception) even in case of cancellation. the only case I can see where this wouldn't happen is if the scope got garbage collected away
f

fitermay

07/27/2022, 11:59 PM
But if I understand you correctly the caller cannot get resumed with cancellation on return
Even though the return could be implicitly performed through a continuation
e

ephemient

07/28/2022, 12:00 AM
what do you mean by "cancellation in return"
f

fitermay

07/28/2022, 12:01 AM
Well a return from a suspend function could really be a continuation under the hood
e

ephemient

07/28/2022, 12:01 AM
as Joffrey said, the model is that cancellation is cooperative and only happens at suspend points
u

uli

07/28/2022, 12:01 AM
@fitermay calling a suspend function does not suspend (until the called function gets to a suspension pint itself) so returning from a suspend function does not resume.
f

fitermay

07/28/2022, 12:01 AM
When one suspend function invokes another the return is not done via a stack
u

uli

07/28/2022, 12:01 AM
yes
e

ephemient

07/28/2022, 12:01 AM
yes, but the caller will always* be resumed
f

fitermay

07/28/2022, 12:01 AM
That's only if you return without suspending first
Resumed without immediately throwing cancellation exception, I assume
What I'm getting is that even if the inner suspend function suspended the return continuation will never throw cancellation exception. I didn't previously know this
@ephemient thanks for explaining
u

uli

07/28/2022, 12:18 AM
Suspend functions do calls and returns through the stack. I just double checked through the kotlin bytecode decompiler. No resuming on return, no cancelation on return.
f

fitermay

07/28/2022, 12:22 AM
How can it return through the stack after suspending?
u

uli

07/28/2022, 12:22 AM
suspend only actually happen when functions like
suspend*Coroutine
are called. I like to call these the ‘leaf’ suspend functions. All other suspend functions are only suspend when the functions they call suspend. I.e. you build up a ‘real’ call stack until you run into a `suspend*Coroutine`call or alike.
f

fitermay

07/28/2022, 12:23 AM
I understand that it only suspends there but the return statement might be after it suspends
And in that cases how can that return be implemented without a continuation?
e

ephemient

07/28/2022, 12:24 AM
can you provide a concrete example? I think you may have a misunderstanding of the coroutine model
u

uli

07/28/2022, 12:24 AM
suspend fun foo() : Int {
 println("Before suspend")
 delay(1)
 println("After suspend")
 return 1
}
All the magic happens around
delay
. entering foo and exiting does not suspend and does not resume
c’mon @ephemient;-)
Go and decompile this to java:
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay

val job = Job()

suspend fun bar(): Int {
    println("Before suspemd")
    delay(10)
    println("After suspemd")
    return 1
}

suspend fun foo() {
    println("Before bar")
    var i = bar()
    println("After bar")
}
e

ephemient

07/28/2022, 12:25 AM
(I meant to ask that to Yuli, if it wasn't clear)
u

uli

07/28/2022, 12:25 AM
sorry @ephemient
The trick is in line 117 where it is checked, if the return value is var5 (IntrinsicsKt.getCOROUTINE_SUSPENDED())
When
delay
is called, bar returns with COROUTINE_SUSPENDED. This is used to signal that bar returned without a result and will return again, later. foo will then also return COROUTINE_SUSPENDED all in all unwrapping the whole call stack.
f

fitermay

07/28/2022, 12:33 AM
I see now
Suspending returns the suspended state all the way up
u

uli

07/28/2022, 12:40 AM
Exactly
That's where the suspending happens. Not at call time
After having all the details straight. Let me emphasize again. Be aware of
suspend fun foo() = withContext {
It is a common pattern and hides a resume and thereby a cancellation point after the inner return
e

ephemient

07/28/2022, 12:56 AM
it's not really different from the equivalent in blocking APIs
fun allocate(): Resource {
    val future = executor.submit { ... }
    return future.get()
}
which can also leak if the current thread is interrupted
f

fitermay

07/28/2022, 1:48 AM
But I think the implementation detail of how return is handled is not obvious. They could've also implemented it by inverting the stack through a continuation
e

ephemient

07/28/2022, 2:08 AM
to truly suspend, there's no choice but to unwind the blocking call stack somehow. the way continuations work could be different but the "return to trampoline" part is inevitable
(at least, as far as present JVMs go, since the call stack can't be reified)
f

fitermay

07/28/2022, 4:39 AM
Right, looking at the disassembly again the return goes through the trampoline which invokes the return continuations
It just happens that in case of standard continuations cancellation exception won't happen during the trampoline execution of return
But if the continuations were CancellableContinuation it could happen