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
  • d

    deviant

    07/12/2017, 6:24 PM
    hi guys i'm trying to implement rx-like
    throttle
    feature with coroutines
    suspend fun <T> ReceiveChannel<T>.consumeThrottled(throttling: Long, action: (T) -> Unit) {
        var timestamp = 0L
        for (data in this) {
            if (timestamp + throttling < System.currentTimeMillis()) {
                timestamp = System.currentTimeMillis()
                action(data)
            }
        }
    }
    is there a proper way?
    d
    • 2
    • 3
  • r

    rogeralsing

    07/12/2017, 6:30 PM
    Some progress on my Proto.Actor for Kotlin coroutines: https://twitter.com/RogerAlsing/status/885204378692579328
    • 1
    • 1
  • j

    janvladimirmostert

    07/16/2017, 8:44 PM
    Quasars gives you the option to handle Futures as fiber-blocking Futures instead of thread-blocking Futures http://blog.paralleluniverse.co/2014/08/12/noasync/ Can something similar be done with Coroutines or is this where the Quasar byte-code instrumentation has an advantage over coroutines ?
    e
    • 2
    • 4
  • a

    ait

    07/18/2017, 7:40 PM
    Hi! I can not figure out how to implement method of 3rd party interface as suspendable when I know that I will call it in suspendable context. What I need is some way to access CoroutineScope of running coroutine (I have some useful data in there) Any hints? I imagine something like ThreadLocal but did not find anything in API.
    f
    • 2
    • 1
  • e

    elizarov

    07/18/2017, 8:25 PM
    @ait There are two choices you have: You can either
    launch
    (fire and forget a new coroutine) or do
    runBlocking
    (to blocking invoking thread while the coroutine is running)
    g
    • 2
    • 2
  • g

    galex

    07/20/2017, 12:41 PM
    Hello, I’ve got a question about coroutines and if what I’m doing is counter-productive: I’ve got 111 urls to download and used coroutines with async {} to do it in parallel. By using CommonPool it takes 10 seconds but by using async(newSingleThreadContext()) per url I get to 6 seconds, almost twice as fast! It’s a gradle plugin meaning a few seconds after downloading all the data the program finishes so I am not worried about the number of threads. Does this makes sense to do it the way I did or is there a better way to be faster while using less threads?
    d
    k
    a
    • 4
    • 20
  • g

    groostav

    07/20/2017, 9:21 PM
    nope, update to that lib, still no good.
    e
    • 2
    • 2
  • r

    rogeralsing

    07/20/2017, 11:37 PM
    this is bloody insane.... our Skynet benchmark runs at 350 ms now... thats twice as fast as Erlang.....
    v
    • 2
    • 8
  • r

    rogeralsing

    07/23/2017, 2:38 PM
    I was more thinking if there was any extra weight to the Job object, if there was a lighter version of the same thing, which just schedules but does not allow for any control of the outcome
    k
    o
    • 3
    • 2
  • e

    elizarov

    07/24/2017, 1:50 PM
    📣 📣 📣
    kotlinx.coroutines
    version 0.17 is released. It has a new
    CompletableDeferred
    primitive;
    Job.join
    and
    Deferred.await
    are waiting for coroutine’s execution on cancellation;
    CoroutineScope.context
    is renamed to
    coroutineContext
    and more. A full list of changes is here: https://github.com/Kotlin/kotlinx.coroutines/blob/master/CHANGES.md
    🎉 11
    ❤️ 2
    👍 10
    v
    g
    • 3
    • 5
  • r

    rafal

    07/24/2017, 2:03 PM
    Is there somewhere an example of using "virtual time" in
    delay
    in tests?
    e
    • 2
    • 4
  • r

    rogeralsing

    07/24/2017, 2:30 PM
    Should the
    kotlinx.coroutines.experimental.TimeoutException
    really be private? I can catch CancellationException which is the base, but still?
    e
    • 2
    • 5
  • o

    omarkj

    07/24/2017, 8:28 PM
    Are there any other pools that ship with coroutines than the CommonPool? The common pool is backed by ForkJoinPool which unfortunately isn’t great for I/O intensive tasks where most the time is spent waiting.
    g
    d
    • 3
    • 7
  • f

    feroz_baig

    07/26/2017, 8:11 AM
    fun main(args: Array<String>) = runBlocking {
                val job = launch(CommonPool) {
                    var nextPrintTime = System.currentTimeMillis()
                    var i = 0
                    while (i < 10) { // computation loop
                        val currentTime = System.currentTimeMillis()
                        if (currentTime >= nextPrintTime) {
                            println("I'm sleeping ${i++} ...")
                            nextPrintTime += 500L
                        }
                    }
                }
                delay(1300L) // delay a bit
                println("main: I'm tired of waiting!")
                job.cancel() // cancels the job
                delay(1300L) // delay a bit to see if it was cancelled....
                println("main: Now I can quit.")
                }
    Why is the job not cancelled after calling it explicitly?
    d
    p
    +3
    • 6
    • 16
  • p

    pilgr

    07/26/2017, 12:25 PM
    How can I handle exception throwing in bg task after Kotlin coroutine is canceled? For now, this leads to app crash. https://stackoverflow.com/questions/45326818/cant-catch-exception-throwing-after-kotlin-coroutine-is-cancelled
    k
    • 2
    • 4
  • r

    rafal

    07/26/2017, 4:22 PM
    that was stupid idea 😛 I've reposted this issue directly to mockito repo (https://github.com/mockito/mockito/issues/1152 )
    e
    • 2
    • 1
  • g

    groostav

    07/27/2017, 6:26 AM
    @voddan at least in principal thats what I'm looking for. What might be important is an efficient way to compute
    StackTrace
    v
    • 2
    • 1
  • f

    feroz_baig

    07/27/2017, 11:04 AM
    Why
    Mutex
    is slower than
    ReentrantLock
    ?
    e
    • 2
    • 7
  • r

    rafal

    07/27/2017, 12:02 PM
    channel.consumeEach {
       if(it.sth()){
         doSth()
      } else {
         // stop consuming - break out of consume
      }
    }
    e
    • 2
    • 1
  • k

    kingsley

    07/27/2017, 9:05 PM
    future {}
    doesn’t return a deferred. It returns a standard
    CompleteableFuture
    and
    await
    is simply an extension function on top of it
    r
    • 2
    • 4
  • r

    rogeralsing

    07/27/2017, 9:40 PM
    Can I get hold of the current ScheduledExecutorService inside a susped fun ?
    e
    • 2
    • 1
  • v

    voddan

    07/31/2017, 11:57 AM
    Is it only me, or try.kotlin.org does not support channels? I get
    java.security.AccessControlException: access denied ("java.util.PropertyPermission" "kotlinx.coroutines.debug" "read")
    when running code with
    import kotlinx.coroutines.experimental.channels.*
    e
    • 2
    • 3
  • k

    kevinherron

    08/03/2017, 9:22 PM
    @elizarov at the end of your talk you mention that you’re working on an IO library - is that work happening in the open anywhere?
    e
    c
    • 3
    • 14
  • f

    feroz_baig

    08/05/2017, 8:14 AM
    Anko's
    bg
    vs Kotlin
    async
    ? Can somebody help me in this
  • e

    elizarov

    08/08/2017, 2:52 PM
    📣
    kotlinx.atomicfu
    version 0.1 was released. This is an utility library that enables writing efficient and idiomatic Kotlin code with atomic variables, CAS, etc, without having to write companion objects with
    j.u.c.a.AtomicXXXFieldUpdater
    instances. It is limited for now (only Maven projects are supported), but that is sufficient to use it in implementation of
    kotlinx.coroutines
    (next version will use it). It is currently published to a separate Bintray repository and will soon be synced to JCenter. More details here: https://github.com/Kotlin/kotlinx.atomicfu/blob/master/README.md
    :kotlin: 3
    👍 6
    v
    g
    m
    • 4
    • 9
  • e

    elizarov

    08/09/2017, 5:20 PM
    It is not hard to follow certain patterns to make sure your code is cancellable: * If you code is like “do something, delay, repeat”, the cancellability comes via
    delay
    * If your code is some CPU-heavy stuff, then you must rememeber to check
    isActive
    periodically * If your code is build with
    generate
    or
    actor
    builder, then you get cancellability “for free” by the virtue of the fact the coroutine’s lifecycle is integrated with lifecycle of the corresponding channel (but you still have to keep in mind CPU-consuming part if you have any of that)
  • k

    kevinherron

    08/10/2017, 12:40 AM
    @elizarov eap of the kotlin plugin or IDEA itself? stepping doesn’t work in the latest release version of IDEA + kotlin plugin
    e
    • 2
    • 1
  • e

    elizarov

    08/10/2017, 7:38 AM
    @anthonyeef If you are using
    kotlinx.coroutines
    library, then its
    async
    function returns a
    Deferred
    object that represent the future result of this asynchronous operation: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/async.html
    a
    • 2
    • 7
  • m

    mikehearn

    08/10/2017, 2:36 PM
    wrt atomicfu - how does it relate to VarHandles? Seems similar in concept, albeit with nicer syntax?
    d
    e
    • 3
    • 3
  • a

    aaverin

    08/10/2017, 2:46 PM
    Hello guys. Got a following situation: AWS m3.large instance = 2CPUs, meaning 1 thread in CommonPool Have a bunch of services that look like:
    fun getData() = async(CommonPool) {
      //do some network
      async(CommonPool) { //do some more parallel network }
      .await() //and process results all together
    }
    Let’s say 3-5 of such written services are called at the same time in parallel by users. Could this lead to any problems?
    k
    • 2
    • 1
Powered by Linen
Title
a

aaverin

08/10/2017, 2:46 PM
Hello guys. Got a following situation: AWS m3.large instance = 2CPUs, meaning 1 thread in CommonPool Have a bunch of services that look like:
fun getData() = async(CommonPool) {
  //do some network
  async(CommonPool) { //do some more parallel network }
  .await() //and process results all together
}
Let’s say 3-5 of such written services are called at the same time in parallel by users. Could this lead to any problems?
k

kingsley

08/10/2017, 2:50 PM
Perhaps you could create your own thread pool context.
CommonPool
isn’t particularly suited for long blocking IO operations. Also, since it is (single?) and blocking, it’s clear why time outs will happen more often
View count: 2