.withlock{} + job.join() = IllegalMonitorStateException

I have a parrent coroutine which uses a lock, and inside of that lock Im launching new coroutines. Everythink worked until I realised that I should join the coroutines before I give away the lock. Using join inside withlock{} gives me the exception (I think thats because another thread which doesnt hold the lock continues the parrent coroutine. A simple delay() inside the lock also gives the same Exception).

java.lang.IllegalMonitorStateException
	at java.util.concurrent.locks.ReentrantReadWriteLock$Sync.tryRelease(ReentrantReadWriteLock.java:371)
	at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1261)
	at java.util.concurrent.locks.ReentrantReadWriteLock$WriteLock.unlock(ReentrantReadWriteLock.java:1131)

What I think I need is either some kind of a (read write) lock which opperates on coroutine level instead of thread level (does this exist?), or some kind of Job.join() which does a bussy wait (not a big deal since the jobs are really short lived). Maybe something like a tryJoin which can be used in a loop. Does Kotlin have anything that can do this things?

Edit: I also tried to use coroutineScope {} instead of job.join() but that also throws the Exception inside of the lock.

You should file a bug on kotl.in/issue, but you should never use Java Lock with coroutines. Use Mutex instead.

Ok I will do the bug issue, could take some time until I make it.

I had read about mutex but completely forgot about that. Something like a read write mutex and reentrant mutex doesn’t exist, right?

There is an issue to add it, but AFAIK it’s not being worked on by anyone right now. https://github.com/Kotlin/kotlinx.coroutines/issues/94

Seems like there will be no reentrant version though: https://github.com/Kotlin/kotlinx.coroutines/issues/1686
Read write is dispensable (I Google translated this word, don’t know if it’s correct) that just hits performance but without reentrant, the structure of the code needs to change, this makes mutex less powerful than locks (for example I have a function x wich needs a lock and another function a which calls that function but needs to do much more synchronised stuff together with that function x so it puts the much more part and the function x into a lock. I can’t simply remove the lock from x just because a is locking anyways because x can also be called from functions which do not use locks. It seems solvable but not
in a nice way).