

Semaphores also provide a setting for being fair (the second argument on their constructor).

Try changing the value provided to the semaphore to anything more than 1! Volatile fields provide memory visibility and guarantee that the value that is being read, comes from the main memory and not the cpu-cache, so the value in cpu-cache is always considered to be dirty, and It has to be fetched again. There’s volatile in Java ( annotation in Kotlin) that can be used on fields. There are multiple ways to achieve this which are explained below. In order to fix this issue, we need to synchronize the work on this value. This is why the final value is not what we expect. This problem can occur in similar other ways, for example, a thread gets past the second level, but before storing it, other threads increment and save the sharedCounter value, and when the first thread jumps in for its third step, it saves an older version of the sharedCounter.

This room has a door that when the room is occupied, is closed.

In the example above, we are launching 1000 coroutines (If you don’t know what they are, just think about them as light-weight threads) on 4 threads, and each of them, increment the global value sharedCounter 1000 times, so the final value of the sharedCounter should be 1000000, but it hardly ever is, unless you get very lucky.īefore we technically explain what is happening here, Imagine there’s one thinking room (the counter) and many people (threads) want to use it but only one person is allowed at a time. Thread-unsafe code which leads to incorrect result
