Whatefficient a simple way to lock access to specific resource in kotlin

590 views Asked by At

We received an assignment where we have to create a distributed file system. This file-system should have multiple servers, each performing a certain function.

This question relates to the lock-server, which is used to prevent two people from writing to the same file at once. Every attempt to access a file generates a thread, that when finished provides access to the requested file. If a file that is not currently free is accessed, the thread should be BLOCKED until the lock is released. With JAVA I would probably just use the wait() and notify() methods, but these are not present in Kotlin (I know you can force them in by casting but it is frowned upon). Is there an elegant way to do this? We are not limited in what libraries we can use so if you know one that could fit I will gladly check it out. Right now the one I think would fit the most is the ReentrantLock, but I am looking for more possibilities.

I have also checked out this list: https://stackoverflow.com/a/35521983/7091281 But none of the ones listed seemed to fit - I specifically need to block the thread, while everything I find does the exact opposite.

BTW the different parts of the system are supposed to communicate via RMI. Also while we can go our own way, it is encouraged to use threads instead of coroutines. (we are supposed to work in JAVA but we were allowed to use kotlin and scala)

1

There are 1 answers

0
ByteWelder On

If you want to use pure Kotlin, you could leverage coroutines, and more specifically its Mutex for locking.

More info can be found at the Kotlin docs, regarding Shared Mutable State and Concurrency