Skip to content

Commit e5863b6

Browse files
authored
Merge pull request #5 from hangga/parallel-slf4j
update
2 parents c87e86f + 43eda09 commit e5863b6

File tree

1 file changed

+70
-57
lines changed

1 file changed

+70
-57
lines changed

core-kotlin-modules/core-kotlin-collections-6/src/test/kotlin/com/baeldung/parallelOperationsCollections/ParallelOperationCollectionsUnitTest.kt

Lines changed: 70 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -10,17 +10,18 @@ import kotlinx.coroutines.flow.*
1010
import kotlinx.coroutines.runBlocking
1111
import org.assertj.core.api.Assertions.assertThat
1212
import org.junit.jupiter.api.Test
13-
import java.text.SimpleDateFormat
13+
import org.slf4j.LoggerFactory
1414
import java.time.Duration
1515
import java.time.Instant
16-
import java.util.*
1716
import java.util.concurrent.Callable
1817
import java.util.concurrent.Executors
1918
import java.util.stream.Collectors
2019

2120

2221
class ParallelOperationCollectionsUnitTest {
2322

23+
private val logger = LoggerFactory.getLogger("")
24+
2425
data class Person(val name: String, val age: Int, var isAdult: Boolean? = null)
2526

2627
private val people = listOf(
@@ -34,31 +35,28 @@ class ParallelOperationCollectionsUnitTest {
3435

3536
private fun List<Person>.assertResultsTrue() {
3637
assertThat(this).containsExactly(
37-
Person("Bob", 16, false),
38-
Person("Alice", 30, true),
39-
Person("Charlie", 40, true),
40-
Person("Ahmad", 42, true)
41-
)
42-
}
43-
44-
private fun Person.setAdult(){
45-
this.isAdult = this.age >= 18
46-
47-
println(
48-
"%-25s %-45s %-40s".format(
49-
SimpleDateFormat("yyyy-MM-dd:HH:mm:ss:SSS").format(Date.from(Instant.now())),
50-
this.toString(),
51-
Thread.currentThread().name
38+
Person("Bob", 16, false),
39+
Person("Alice", 30, true),
40+
Person("Charlie", 40, true),
41+
Person("Ahmad", 42, true)
5242
)
53-
)
5443
}
5544

5645
private fun String.printAsHeader() {
57-
println("$this ${"-".repeat(100 - this.length)}\n${"%-25s %-45s %-40s".format("Time", "Operation", "Thread name")}")
46+
logger.info("{} {}", "-".repeat(32 - Thread.currentThread().name.length), this)
47+
}
48+
49+
private fun Person.setAdult() {
50+
this.isAdult = this.age >= 18
51+
val line = " ".repeat(32 - Thread.currentThread().name.length)
52+
logger.info("{} {}", line, this)
5853
}
5954

6055
private fun Instant.printTotalTime() {
61-
println("Total time taken: ${Duration.between(this, Instant.now()).toMillis()} ms\n")
56+
val totalTime = Duration.between(this, Instant.now()).toMillis()
57+
logger.info(
58+
"{} Total time taken: {} ms \n", "-".repeat(32 - Thread.currentThread().name.length), totalTime
59+
)
6260
}
6361

6462
@Test
@@ -67,11 +65,11 @@ class ParallelOperationCollectionsUnitTest {
6765
val startTime = Instant.now()
6866

6967
val filteredPeople = people.map { person ->
70-
async {
71-
person.setAdult()
72-
person
73-
}
74-
}.awaitAll().filter { it.age > 15 }.sortedBy { it.age }
68+
async {
69+
person.setAdult()
70+
person
71+
}
72+
}.awaitAll().filter { it.age > 15 }.sortedBy { it.age }
7573

7674
startTime.printTotalTime()
7775

@@ -85,13 +83,15 @@ class ParallelOperationCollectionsUnitTest {
8583
val startTime = Instant.now()
8684

8785
val filteredPeople = people.asFlow().flatMapMerge { person ->
88-
flow {
89-
emit(async {
90-
person.setAdult()
91-
person
92-
}.await())
93-
}
94-
}.filter { it.age > 15 }.toList().sortedBy { it.age }
86+
flow {
87+
emit(
88+
async {
89+
person.setAdult()
90+
person
91+
}.await()
92+
)
93+
}
94+
}.filter { it.age > 15 }.toList().sortedBy { it.age }
9595

9696
startTime.printTotalTime()
9797

@@ -103,12 +103,17 @@ class ParallelOperationCollectionsUnitTest {
103103
"Using RxJava".printAsHeader()
104104
val startTime = Instant.now()
105105

106-
val observable = Observable.fromIterable(people).flatMap({
107-
Observable.just(it).subscribeOn(Schedulers.computation()).doOnNext { person ->
108-
person.setAdult()
109-
}
110-
}, people.size) // Uses maxConcurrency for the number of elements
111-
.filter { it.age > 15 }.toList().map { it.sortedBy { person -> person.age } }.blockingGet()
106+
val observable = Observable.fromIterable(people).flatMap(
107+
{
108+
Observable.just(it).subscribeOn(Schedulers.computation()).doOnNext { person ->
109+
person.setAdult()
110+
}
111+
}, people.size // Uses maxConcurrency for the number of elements
112+
)
113+
.filter { it.age > 15 }
114+
.toList()
115+
.map { it.sortedBy { person -> person.age } }
116+
.blockingGet()
112117

113118
startTime.printTotalTime()
114119

@@ -120,12 +125,16 @@ class ParallelOperationCollectionsUnitTest {
120125
"Using RxKotlin".printAsHeader()
121126
val startTime = Instant.now()
122127

123-
val observable = people.toObservable().flatMap({
124-
Observable.just(it).subscribeOn(Schedulers.computation()).doOnNext { person ->
125-
person.setAdult()
126-
}
127-
}, people.size) // Uses maxConcurrency for the number of elements
128-
.filter { it.age > 15 }.toList().map { it.sortedBy { person -> person.age } }.blockingGet()
128+
val observable = people.toObservable().flatMap(
129+
{
130+
Observable.just(it).subscribeOn(Schedulers.computation()).doOnNext { person ->
131+
person.setAdult()
132+
}
133+
}, people.size // Uses maxConcurrency for the number of elements
134+
).filter { it.age > 15 }
135+
.toList()
136+
.map { it.sortedBy { person -> person.age } }
137+
.blockingGet()
129138

130139
startTime.printTotalTime()
131140

@@ -137,10 +146,12 @@ class ParallelOperationCollectionsUnitTest {
137146
"Using RxKotlin 1 thread".printAsHeader()
138147
val startTime = Instant.now()
139148

140-
val observable =
141-
people.toObservable().subscribeOn(Schedulers.io()).flatMap { Observable.just(it) }.doOnNext { person ->
142-
person.setAdult()
143-
}.filter { it.age > 15 }.toList().map { it.sortedBy { person -> person.age } }.blockingGet()
149+
val observable = people.toObservable()
150+
.subscribeOn(Schedulers.io())
151+
.flatMap { Observable.just(it) }
152+
.doOnNext { person -> person.setAdult() }
153+
.filter { it.age > 15 }.toList()
154+
.map { it.sortedBy { person -> person.age } }.blockingGet()
144155

145156
startTime.printTotalTime()
146157

@@ -153,10 +164,11 @@ class ParallelOperationCollectionsUnitTest {
153164
val startTime = Instant.now()
154165

155166
val filteredPeople = people.parallelStream().map { person ->
156-
157-
person.setAdult()
158-
person
159-
}.filter { it.age > 15 }.sorted { p1, p2 -> p1.age.compareTo(p2.age) }.collect(Collectors.toList())
167+
person.setAdult()
168+
person
169+
}.filter { it.age > 15 }
170+
.sorted { p1, p2 -> p1.age.compareTo(p2.age) }
171+
.collect(Collectors.toList())
160172

161173
startTime.printTotalTime()
162174

@@ -170,11 +182,11 @@ class ParallelOperationCollectionsUnitTest {
170182

171183
val executor = Executors.newFixedThreadPool(people.size)
172184
val futures = people.map { person ->
173-
executor.submit(Callable {
174-
person.setAdult()
175-
person
176-
})
177-
}.map { it.get() }.filter { it.age > 15 }.sortedBy { it.age }
185+
executor.submit(Callable {
186+
person.setAdult()
187+
person
188+
})
189+
}.map { it.get() }.filter { it.age > 15 }.sortedBy { it.age }
178190

179191
executor.shutdown()
180192

@@ -183,3 +195,4 @@ class ParallelOperationCollectionsUnitTest {
183195
futures.assertResultsTrue()
184196
}
185197
}
198+

0 commit comments

Comments
 (0)