Coroutine not respecting mutex.lock hence more than one coroutine entering the safe code at a time

I have a shared piece of code in a function, that should be accessed one at a time . I used mutex.lock/unlock to achieve this while working with coroutines.

 public class TestAbc {
 val mutex = Mutex()
    suspend fun testfunction() {
        hashmap.put("abc", "efg")

public class InitiatorClass{
val testAbc: TestAbc = TestAbc()

    public fun startJob() {
        GlobalScope.launch {

I tested this by calling Start Job Function twice from a java class ,from different threads.

wanted only one coroutine to access these two dataStructures at once, with help of mutex but its not working.I see multiple coroutines entering the lock.

Hi @rahuldps1992,
your code is pretty strange.

You have defined a mutex for each TestAbc, but arrayList and hashmap look shared.

Can you rewrite your example, please?
Having a reproducible bug is a really good starting point.

1 Like

Hey i figured out the issue.I was creating multiple instances of InitiatorClass.That was the issue.