Skip to content

Instantly share code, notes, and snippets.

@edujtm
Created July 11, 2019 01:13
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 edujtm/486f4db07ac5c8662ecd84da8e739f96 to your computer and use it in GitHub Desktop.
Save edujtm/486f4db07ac5c8662ecd84da8e739f96 to your computer and use it in GitHub Desktop.
Reddit answer to threading question
import kotlinx.coroutines.*
// this will execute on background thread
suspend fun getDataFromDatabase() : Array<Int> = withContext(Dispatchers.IO) {
delay(1000)
println("Thread name inside context: ${Thread.currentThread().name}")
Array(10) { i -> i }
}
fun main(args : Array<String>) = runBlocking {
// CoroutineScope is like a handle that you can use to control your coroutines
// As far as I understand, related coroutines should be launched from the same scope.
// If one of them fails, all other will be canceled (unless you're using supervisorscope)
val coroutineScope = this
// On android you would use Dispatchers.Main for android UI thread
// val coroutineScope = CoroutineScope(Dispatchers.Main)
var jobNames = arrayOf<Int>()
// will launch on main thread
val job = coroutineScope.launch {
jobNames = getDataFromDatabase()
// this will be scheduled to execute on the main thread (meaning it can make changes on the UI)
println(jobNames.joinToString(prefix = "[", postfix = "]"))
println("Thread name inside coroutine: ${Thread.currentThread().name}")
}
// count will be zero
var count = jobNames.size
// Will not execute
for (i in 1..count) {
println("count inside loop: $count")
}
// count will still be zero
println("count outside loop: $count")
job.join()
count = jobNames.size;
println("Count again: $count")
println("Thread name on main function: ${Thread.currentThread().name}")
}
fun main(args : Array<String>) {
var jobNames = arrayOf<Int>();
val thread = object : Thread() {
override fun run() {
try {
Thread.sleep(1000); // Simulates the time to query the database
// Simulates return from database
jobNames = Array(10, { i -> i });
// Just to make understanding a bit clearer
println(jobNames.joinToString(prefix = "[", postfix = "]"))
} catch ( e : Exception) {
e.printStackTrace();
}
}
}
// Executing main thread
// Starts execution on a background thread
thread.start(); // Will execute on another thread, without stopping the main thread to wait for the database result
// Basically what happens here is like a bifurcation on the road,
// but instead of roads, you have code sections executing in parallel
// Still executing main thread here
// So jobNames will probably be empty when execution reaches this line
println(jobNames.joinToString(prefix = "[", postfix = "]"))
// count will probably be zero
val count = jobNames.size;
for (i in 1..count) {
// This code will probably not execute
println("Count size inside for loop: ${count}")
}
// Count will still probably be zero
println("Count size outside for loop: ${count}")
// Waits for the background thread
thread.join();
}
fun main(args : Array<String>) {
var jobNames = arrayOf<Int>();
val thread = object : Thread() {
override fun run() {
try {
Thread.sleep(1000); // Simulates the time to query the database
// Simulates return from database
jobNames = Array(10, { i -> i });
} catch ( e : Exception) {
e.printStackTrace();
}
}
}
// Executing main thread
// Starts execution on a background thread
thread.start(); // Will execute on another thread, without stopping the main thread to wait for the database result
// Now we can explicitly wait for the other thread to finish it's execution
// and then we will have the result of the database
thread.join();
// But this approach blocks the main thread, which is not desirable (and makes the other thread useless basically)
// Still executing main thread here
// So jobNames will have result from database
println(jobNames.joinToString(prefix = "[", postfix = "]"))
// count will be 10
val count = jobNames.size;
// Will execute 10 times
for (i in 1..count) {
println("Count size inside for loop: ${count}")
}
// Count will be 10
println("Count size outside for loop: ${count}")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment