Last active
September 26, 2019 13:06
-
-
Save glebmtb/b15272106aff6a8f6fbbeb54a797be76 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
fun def1(par: String) = | |
//Вызов которые нельзя менять | |
GlobalScope.async { | |
println(par + "-1: " + System.currentTimeMillis()) | |
Thread.sleep(1000) | |
if (par == "3") throw RuntimeException("error '3'") | |
par + "_map1" | |
} | |
fun def2(list: List<String>) = | |
GlobalScope.async { | |
list.map { str -> | |
println(str + "-2: " + System.currentTimeMillis()) | |
Thread.sleep(1000) | |
str.plus("_map2") | |
} | |
} | |
fun main() { | |
val list = listOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10") | |
val start = System.currentTimeMillis() | |
runBlocking { | |
val reult = list | |
.map { def1(it) } | |
.mapNotNull { | |
try { | |
it.await() | |
} catch (e: Exception) { | |
println("Error: " + e.message) | |
null | |
} | |
} | |
.chunked(2) | |
.map { def2(it) } | |
.flatMap { it.await() }.toSet() | |
println(reult) | |
} | |
val timeRun = System.currentTimeMillis()-start | |
println("Run $timeRun ms") | |
} |
Output:
2-1: 1569502273180
3-1: 1569502273182
4-1: 1569502273182
5-1: 1569502274186
6-1: 1569502274187
7-1: 1569502274187
8-1: 1569502274187
Error: error '3'
10-1: 1569502275190
9-1: 1569502275190
4_map1-2: 1569502276196
6_map1-2: 1569502276196
1_map1-2: 1569502276196
8_map1-2: 1569502276196
5_map1-2: 1569502277201
2_map1-2: 1569502277201
7_map1-2: 1569502277201
9_map1-2: 1569502277201
10_map1-2: 1569502278206
[1_map1_map2, 2_map1_map2, 4_map1_map2, 5_map1_map2, 6_map1_map2, 7_map1_map2, 8_map1_map2, 9_map1_map2, 10_map1_map2]
Run 6092 ms
Попробуйте ответить для себя на следующие вопросы:
- есть ли проблемы в коде метода main?
- можно ли оптимизировать код метода main?
- почему увеличением числа в chunked деградирует систему, при значении 4 время выполнения уже 7 секунд, и чем выше число тем дольше будет выполняться?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
вырезал бизнес логику заменив ее конкатенацией стрингов(def функции), а структуру кода оставил.