Nitesh
09/01/2023, 9:26 AMhho
09/01/2023, 9:29 AMobject
is dealt with by Kotlin. Everything inside you have to synchronize yourself.Nitesh
09/01/2023, 9:30 AMhho
09/01/2023, 9:30 AMNitesh
09/01/2023, 9:37 AMNitesh
09/01/2023, 9:50 AMKlitos Kyriacou
09/01/2023, 9:56 AM++
is not an atomic operation. It involves reading and then writing. You should consider using AtomicInteger.incrementAndGet()
(or getAndIncrement()
).Nitesh
09/01/2023, 10:06 AMKlitos Kyriacou
09/01/2023, 10:09 AMJasjeet Singh
09/01/2023, 10:15 AMJoffrey
09/01/2023, 10:33 AMNitesh
09/01/2023, 10:39 AMKlitos Kyriacou
09/01/2023, 10:44 AMNitesh
09/01/2023, 10:45 AMKlitos Kyriacou
09/01/2023, 10:49 AMJasjeet Singh
09/01/2023, 10:52 AMJasjeet Singh
09/01/2023, 10:53 AMJasjeet Singh
09/01/2023, 10:56 AMJasjeet Singh
09/01/2023, 10:58 AMKlitos Kyriacou
09/01/2023, 10:59 AMfun testMultipleThreadsForMetricsObject() {
thread(start = true) {
repeat(100_000) {
MyObject.data++
}
}
thread(start = true) {
repeat(100_000) {
MyObject.data++
}
}
Thread.sleep(3000)
Assertions.assertEquals(200_000, MyObject.data)
}
This is still not deterministic, but it will fail most of the time, with different actual values of MyObject.data each time.Joffrey
09/01/2023, 11:07 AMWout Werkman
09/01/2023, 12:19 PMHow do we ensure to write deterministic tests?If you want to test your concurrent algorithm, there are extremely useful frameworks for this such as Lincheck. Even after trying to implement seemingly simple concurrent algorithms, you will be baffled by how difficult it is. Lincheck named above has been used to find bugs in
java.util.concurrent.ConcurrentLinkedDeque
that are yet to be fixed by extremely smart developers.
The best thing to do, is to not use mutable state like @Joffrey recommended. Otherwise always use locks, atomic operations or existing concurrent data structures and thank whatever you believe in every day that people implemented these complicated things for you 🙂