https://kotlinlang.org logo
Title
y

y

05/07/2023, 1:36 PM
class Foo {
    private val someConcurrentCollection = //...
    
    fun addToCollection(val s: String) {
        if (!checkS(s)) {
            return
        }

        synchronized(this) {
            val t = doSomethingToS(s)
            someConcurrentCollection.add(t)
        }
    }
}

fun checkS(s: String): Boolean = //...
I have something that kind of looks like this. does the fact that a thread is currently in the
synchronized
block, completely prevents other threads from entering the
addToCollection()
function and running
checkS()
? same for the other way around, do multiple threads with
s
values such that
checkS(s) = false
stop 'legitimate' threads from entering
addToCollection()
?
j

Joffrey

05/07/2023, 1:44 PM
Only the synchronized block is non-concurrent. Other threads can call
checkS
. They will only stop at the beginning of the
synchronized
block if one thread is already there.
y

y

05/07/2023, 1:44 PM
great! thank you
r

Rob Elliot

05/08/2023, 1:49 PM
Beware of check-then-act race conditions if the check isn’t protected by the same guard as the action. Two threads could both see checkS as true, and both would then call doSomethingToS, just one after the other. Perhaps that’s ok.
j

Joffrey

05/08/2023, 2:58 PM
Ah yeah of course it depends on the semantics you're trying to achieve. It seemed to me that the OP just wanted to protect the list interaction so no 2 threads would do it at the same time, but your point is quite important if I misunderstood the purpose
y

y

05/08/2023, 3:02 PM
@Rob Elliot fortunately @Joffrey is correct about my actual use case, but that is a great point