Skip to content

Instantly share code, notes, and snippets.

@IgorGanapolsky
Created September 25, 2018 15:54
Show Gist options
  • Save IgorGanapolsky/a6cf696ebd5aebc7a590b476a24218a8 to your computer and use it in GitHub Desktop.
Save IgorGanapolsky/a6cf696ebd5aebc7a590b476a24218a8 to your computer and use it in GitHub Desktop.
Coroutines are cheaper than threads!
import kotlinx.coroutines.experimental.CoroutineName
import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.delay
import java.text.SimpleDateFormat
import java.util.*
/**
* Coroutines are cheaper than threads!
*/
fun main(args: Array<String>) {
for (i in 1..1_000_000) {
async(CoroutineName("UseCase")) {
log("atomicInteger1: " + atomicInteger1.addAndGet(i).toString())
log("atomicInteger2: " + atomicInteger2.addAndGet(i).toString())
log("atomicInteger3: " + atomicInteger3.addAndGet(i).toString())
delay(1000L) // the resulting program won't run for 1,000,000 seconds (over 11.5 days)!
}
}
}
/** Custom logger */
private fun log(msg: String) {
val sdf = SimpleDateFormat("hh:mm:ss:ms", Locale.getDefault())
val currentTime = sdf.format(Date())
println("[${"'Work in thread " + Thread.currentThread().name + "; Time: " + currentTime}] value: $msg")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment