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
s

Slackbot

06/10/2021, 11:49 AM
This message was deleted.
c

CLOVIS

06/10/2021, 12:07 PM
If you create a thread pool with a single thread, then you are guaranteed that coroutines will resume in the same thread (https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/new-single-thread-context.html), not sure if that's enough for you?
e

Erik

06/10/2021, 12:34 PM
Maybe, but what if I want a dynamically growing (and shrinking?) thread pool with configurable maximum size? I think that
<http://Dispatchers.IO|Dispatchers.IO>
does that with a default maximum size of 64 threads (https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-i-o.html)
With more than 1 thread only, I can have a bit more concurrency: while one operation is suspended (blocking a thread), another operation can still happen (on another thread). That isn't possible with just one thread, I think, if the library (Realm) does blocking operations.
u

Ulrik Rasmussen

06/10/2021, 12:51 PM
You should avoid blocking coroutines. If your operation is blocking, you should wrap just that operation in
withContext(<http://Dispatchers.IO|Dispatchers.IO>) { ... }
. This will allow your single thread pool to continue working while the operation is suspended on the
IO
dispatcher.
e

Erik

06/10/2021, 1:45 PM
I see your point, and its similar to the point that I was trying to make, but I think I made a fundamental mistake. So I'm deleting my question. Thanks!
c

CLOVIS

06/10/2021, 7:08 PM
There are no stupid questions. I think it should be possible to do what you want, but I honestly don't know how. Hopefully someone more knowledgeable comes in
e

Erik

06/10/2021, 7:51 PM
A single threaded context is an idea, but the issue is that Realm requires access to all its live instances on the same thread. So blocking IO operations must happen on the same thread. I cannot switch to the IO dispatcher for that.
Alternatively I could try to obtain an instance of the thread-confined objects (often multiple) after switching to the IO dispatcher. Then I can just do all the blocking stuff I want. Trouble is: how? I would be passing around a lot of lambdas instead of actual instances. That's likely too complex.
c

CLOVIS

06/10/2021, 8:46 PM
Not really adding anything but it seems really weird to me that a lib would do blocking IO with objects confined to a single thread. Blocking IO is usually the number 1 thing people want to parallelize or do in another thread
e

Erik

06/11/2021, 6:28 AM
Welcome to Realm for Android!
It has synchronous (blocking) APIs and asynchronous APIs. The latter are also thread confined in a different way: they must run on a thread with a
Looper
. By default that's the main thread only, which invites doing database stuff from UI classes. Yes, I'm talking years back when these kinds of things happened. Now it's 2021 and that's the legacy I'm trying to modernize.
u

Ulrik Rasmussen

06/11/2021, 6:32 AM
If your library really requires all blocking calls to be executed on the same thread, couldn't you then create a dedicated, single-threaded dispatcher and just use
withContext(yourSingleThreadedDispatcher) { .. }
instead of
<http://Dispatchers.IO|Dispatchers.IO>
? It sounds strange, though
e

Erik

06/11/2021, 6:36 AM
Yes, that's possible, but very much impractical, because all objects produced by Realm are also bound to that thread (and to the open Realm instance). 2 options (at least): • Don't pass around these objects, because you also need to pass the thread with them and keep the Realm open. • Obtain a Realm instance on every thread where you might need to CRUD any data. That breaks unidirectional data flow. And has serious concurrency issues
The first option basically means that I need a global/singleton single thread context to which I have to delegate everything. Even reading a simple property needs to happen on the correct thread!
Alternatively, Realm offers to copy objects into memory. That can easily lead to memory issues because copies often need to be deeper than you want. It's also the fault of my data models, but that's also the legacy that I deal with
Yet another option is to freeze a Realm to make it thread safe. It becomes read only and it is stored in disk. Trouble is: the original hot Realm must stay open.
c

CLOVIS

06/11/2021, 7:28 AM
Honestly I think your best bet is to have a single thread context and delegate to it. It won't require much work from your end, it's not perfect but it's still much better than using the main thread, and you can have coroutines properly everywhere else in the project. Create a wrapper class for your realm instance and have that context in it, and force the rest of the code to access it from there, and it should be fine
e

Erik

06/11/2021, 8:09 AM
Trouble is: even if I get an entity instance from a Realm db, that too must be accessed from that same single thread. So even if I want to read
person.name
I must know the thread I must do that on. 🤦‍♂️ It's like the opposite of the 'shared mutable state' problem. It's unshared mutable state. As in: unshareable. And mutable from multiple threads. That mutability is what I can confine to one thread, but that doesn't give me the freedom to read from any thread. I just cannot pass around instances without also knowing the single thread to CRUD on. Wrapping every CRUD operation in a singleton single threaded context might be possible, but that sounds like horrible design.
c

CLOVIS

06/11/2021, 8:34 AM
I'm not saying it's good design, just that it's better than having to do everything in the main thread 😅 Depending on how complex your data is, it could be possible to wrap CRUD in the single thread context, and copy all objects that come from there so other threads can access them?
This way, you'd have a ‘realm wrapper' that does your operations in a single thread, but everything else in your app would run in whatever you want (and you would never block the main thread)
e

Erik

06/13/2021, 6:19 AM
We tried that approach, but copies needed to be deeper than was possible with available memory. The data models are too complex for that. If we'd want that approach, we'd need to extract only the data needed into UI specific models, but that's too much work at this time. In any case it's a lot of work. Decoupling UI models from Realm models and behaviour would be an important step forward. Any approach likely needs that, ultimately.