Skip to content

Instantly share code, notes, and snippets.

@aaccioly
Last active January 14, 2023 21:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaccioly/1781f9c08128a8f0c03fc386973eb918 to your computer and use it in GitHub Desktop.
Save aaccioly/1781f9c08128a8f0c03fc386973eb918 to your computer and use it in GitHub Desktop.
My version of Rock the JVM Kotlin Coroutines Tutorial: https://youtu.be/Wpco6IK1hmY and https://youtu.be/2RdHD0tceL4 (Gradle)
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("jvm") version "1.8.0"
application
}
group = "com.rockthejvm.blog"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
}
dependencies {
testImplementation(kotlin("test"))
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4")
implementation("ch.qos.logback:logback-classic:1.4.5")
implementation("io.github.microutils:kotlin-logging-jvm:3.0.4")
}
tasks.test {
useJUnitPlatform()
}
tasks.withType<KotlinCompile> {
kotlinOptions.jvmTarget = "17"
}
application {
mainClass.set("com.rockthejvm.blog.CoroutinesPlaygroundKt")
}
package com.rockthejvm.blog
import kotlinx.coroutines.*
import mu.KotlinLogging
import java.util.concurrent.Executors
// coroutine = "thread"
// parallel + concurrent apps
private val logger = KotlinLogging.logger {}
suspend fun bathTime() {
// Continuation = data structure stores all local context
logger.info("Going to the bathroom")
delay(500L) // suspends/"blocks" the computation
// Continuation restored here
logger.info("Bath done, exiting")
}
suspend fun boilingWater() {
logger.info("Boiling water")
delay(500L)
logger.info("Water boiled")
}
suspend fun makeCoffee() {
logger.info("Starting to make coffee")
delay(500L)
logger.info("Done with coffee")
}
suspend fun sequentialMorningRoutine() {
coroutineScope {// start a "context" for coroutines
bathTime()
// add more code, including suspend functions
// parallel code here, all needs to finish before the scope is closed
}
coroutineScope {
makeCoffee()
}
}
suspend fun eatMyBreakfast() {
logger.info("Starting to eat")
delay(500L)
logger.info("Done eating")
}
suspend fun concurrentMorningRoutine() {
coroutineScope {
launch { bathTime() } // this coroutine is a CHILD of the coroutineScope
launch { makeCoffee() }
}
}
@OptIn(DelicateCoroutinesApi::class)
suspend fun noStructConcurrentMorningRoutine() {
GlobalScope.launch { bathTime() }
GlobalScope.launch { makeCoffee() }
}
suspend fun morningRoutineWithCoffee() {
coroutineScope {
val bathTimeJob = launch { bathTime() }
val boilingWaterJob = launch { boilingWater() }
bathTimeJob.join()
boilingWaterJob.join()
launch { makeCoffee() }
}
}
// structured concurrency
suspend fun morningRoutineWithCoffeeStructured() {
coroutineScope {
coroutineScope {
// parallel jobs
launch { bathTime() }
launch { boilingWater() }
}
// both coroutines are done
launch { makeCoffee() }
}
}
// return values from coroutines
suspend fun preparingJavaCoffee(): String {
logger.info("Starting to make coffee")
delay(500L)
logger.info("Done with coffee")
return "Java coffee"
}
suspend fun toastingBread(): String {
logger.info("Starting to toast bread")
delay(1000L)
logger.info("Toast is out!")
return "Toasted bread"
}
suspend fun prepareBreakfast() {
coroutineScope {
val coffee = async { preparingJavaCoffee() } // Deferred = analogous to Future
val toast = async { toastingBread() }
// semantic blocking
val finalCoffee = coffee.await()
val finalToast = toast.await()
logger.info { "I'm eating $finalToast and drinking $finalCoffee" }
}
}
// cooperative scheduling - coroutines yield manually
suspend fun workingHard() {
logger.info("Working hard")
// CPU-intensive computation
while(true) {
// do some hard work
}
delay(100L)
logger.info("Work done")
}
suspend fun workingNicely() {
logger.info("Working")
// CPU-intensive computation
while(true) {
delay(100L) // give a chance for the dispatcher to run another coroutine
}
delay(100L)
logger.info("Work done")
}
suspend fun takeABreak() {
logger.info("Taking a break")
delay(1000L)
logger.info("Break done")
}
@OptIn(ExperimentalCoroutinesApi::class)
suspend fun workHardRoutine() {
val dispatcher: CoroutineDispatcher = Dispatchers.Default.limitedParallelism(1) // force 1 thread
coroutineScope {
launch(dispatcher) {
workingHard()
}
launch(dispatcher) {
takeABreak()
}
}
}
@OptIn(ExperimentalCoroutinesApi::class)
suspend fun workNicelyRoutine() {
val dispatcher: CoroutineDispatcher = Dispatchers.Default.limitedParallelism(1) // force 1 thread
coroutineScope {
launch(dispatcher) {
workingNicely()
}
launch(dispatcher) {
takeABreak()
}
}
}
val simpleDispatcher = Dispatchers.Default // "normal code" = short code or yielding coroutines
val blockingDispatcher = Dispatchers.IO // "blocking code" (e.g. DB Connections, long-running computations)
val customDispatcher = Executors.newFixedThreadPool(8).asCoroutineDispatcher() // on top of your own thread pool
// cancellation
suspend fun forgettingFriendBirthdayRoutine() {
coroutineScope {
val workingJob = launch { workingNicely() }
launch {
delay(2000L) // after 2s I remember I have a birthday today
workingJob.cancel() // sends a SIGNAL to the coroutine to cancel, cancellation happens at first yielding point
workingJob.join() // you are sure that the coroutine has been cancelled
logger.info("I forgot my friend's birthday! Buying a present now!")
}
}
}
// if a coroutine doesn't yield it can't be cancelled
suspend fun forgettingFriendBirthdayRoutineUncancelable() {
coroutineScope {
val workingJob = launch { workingHard() }
launch {
delay(2000L)
logger.info("Trying to stop working...")
workingJob.cancel() // sends a SIGNAL to the coroutine to cancel, cancellation happens at first yielding point (NEVER)
workingJob.join()
logger.info("I forgot my friend's birthday! Buying a present now!") // won't print
}
}
}
// resources
class Desk : AutoCloseable {
init {
logger.info("Starting to work on this desk")
}
override fun close() {
logger.info("Cleaning up the desk")
}
}
suspend fun forgettingFriendBirthdayRoutineWithResource() {
val desk = Desk()
coroutineScope {
val workingJob = launch {
desk.use {_ -> // this resource will be closed upon completion of the coroutine
workingNicely()
}
}
// can also define your own "cleanup" code in case of completion
workingJob.invokeOnCompletion { _: Throwable? ->
// can handle completion and cancellation differently, depending on the exception
logger.info("Make sure I tell to my colleagues that I'll be out for 30 mins")
}
launch {
delay(2000L)
workingJob.cancel()
workingJob.join()
logger.info("I forgot my friend's birthday! Buying a present now!")
}
}
}
suspend fun drinkWater() {
while(true) {
logger.info("Drinking water")
delay(1000L)
}
}
// cancellation propagates to child coroutines
suspend fun forgettingFriendBirthdayRoutineStayHydrated() {
coroutineScope {
val workingJob = launch {
launch { workingNicely() }
launch { drinkWater() }
}
launch {
delay(2000L)
workingJob.cancel()
workingJob.join()
logger.info("I forgot my friend's birthday! Buying a present now!")
}
}
}
// coroutines context
suspend fun asynchronousGreeting() {
coroutineScope {
launch(CoroutineName("Greeting Coroutine") + Dispatchers.Default /* these two = CoroutineContext */) {
logger.info("Hello, everyone!")
}
}
}
suspend fun demoContextInheritance() {
coroutineScope {
launch(CoroutineName("Greeting Coroutine")) {
logger.info("[parent coroutine] Hello!")
launch(CoroutineName("Child Greeting Coroutine")) {// coroutine context will be inherited here
logger.info("[child coroutine] Hi there!")
}
delay(200)
logger.info("[parent coroutine] Hi again from parent!")
}
}
}
suspend fun main() {
demoContextInheritance()
}
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="CoroutinesPlaygroundKt" type="JetRunConfigurationType" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="com.rockthejvm.blog.CoroutinesPlaygroundKt" />
<module name="rockthejvm-coroutines.main" />
<shortenClasspath name="NONE" />
<option name="VM_PARAMETERS" value="-Dkotlinx.coroutines.debug" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
</component>
MIT License
Copyright (c) 2022 Riccardo Cardin
Copyright (c) 2023 Anthony Accioly
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@aaccioly
Copy link
Author

Original version by @rcardin here: https://github.com/rcardin/kotlin-coroutines-playground . My version has deviated a bit from it as I was following the videos.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment