Created
October 3, 2019 20:29
-
-
Save bitkid/68fd50575f35ab456f5b03a7746437f2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.CoroutineScope | |
import kotlinx.coroutines.GlobalScope | |
import kotlinx.coroutines.channels.Channel | |
import kotlinx.coroutines.channels.ReceiveChannel | |
import kotlinx.coroutines.channels.SendChannel | |
import kotlinx.coroutines.delay | |
import kotlinx.coroutines.launch | |
import java.io.File | |
import java.util.concurrent.CountDownLatch | |
import kotlin.system.measureTimeMillis | |
data class UploadResponse(val code: Int, | |
val message: String, | |
val file: File) | |
fun CoroutineScope.uploadWorker(files: ReceiveChannel<File>, | |
responses: SendChannel<UploadResponse>) { | |
launch { | |
for (file in files) { | |
// this simulates the http client call | |
delay(2000) | |
responses.send(UploadResponse(200, "done", file)) | |
println("upload file ${file.name} on thread ${Thread.currentThread().name}") | |
} | |
} | |
} | |
fun CoroutineScope.uploadResponseHandler(responses: ReceiveChannel<UploadResponse>, | |
latch: CountDownLatch) { | |
launch { | |
for (response in responses) { | |
println("upload had status ${response.code}") | |
latch.countDown() | |
} | |
} | |
} | |
fun CoroutineScope.uploader(files: ReceiveChannel<File>, | |
latch: CountDownLatch, | |
nrOfWorkers: Int = 4) { | |
val responses = Channel<UploadResponse>() | |
repeat(nrOfWorkers) { uploadWorker(files, responses) } | |
uploadResponseHandler(responses, latch) | |
} | |
object UploadMain { | |
@JvmStatic | |
fun main(args: Array<String>) { | |
val files = (1..10).map { File("$it") } | |
val latch = CountDownLatch(files.size) | |
val channel = Channel<File>() | |
val time = measureTimeMillis { | |
GlobalScope.launch { | |
uploader(channel, latch) | |
files.forEach { | |
channel.send(it) | |
} | |
} | |
latch.await() | |
} | |
println(time) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment