From bea9baa539d1defa29ea10d99fe8acf9e7f88b93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcin=20Moska=C5=82a?= Date: Tue, 12 Nov 2019 17:07:28 +0100 Subject: [PATCH] Eliminate potential conflict `number` is in a critical section as modified by multiple threads - there is a possibility that two threads will try to modify it at the same time and so the result is uncertain. It either needs to be synchronized with `Mutex`, channel, or we need to use `AtomicInteger`. --- src/Async.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Async.kt b/src/Async.kt index 9269697..602e384 100644 --- a/src/Async.kt +++ b/src/Async.kt @@ -31,7 +31,7 @@ fun Application.async(random: Random = Random(), delayProvider: DelayProvider = private suspend fun ApplicationCall.respondHandlingLongCalculation(random: Random, delayProvider: DelayProvider, startTime: Long) { val queueTime = System.currentTimeMillis() - startTime - var number = 0 + var number = AtomicInteger() val computeTime = measureTimeMillis { // We specify a coroutine context, that will use a thread pool for long computing operations. // In this case it is not necessary since we are "delaying", not sleeping the thread. @@ -40,7 +40,7 @@ private suspend fun ApplicationCall.respondHandlingLongCalculation(random: Rando withContext(compute) { for (index in 0 until 300) { delayProvider(10) - number += random.nextInt(100) + number.addAndGet(random.nextInt(100)) } } }