I'm writing a database in Kotlin, and don't have a...
# getting-started
g
I'm writing a database in Kotlin, and don't have a solid understanding of concurrency fundamentals Traditionally, you'd use Read-Write Locks for I/O operations like reading/writing to disk If I'm using Kotlin Coroutines, what's the best practice for ensuring that multiple concurrent reads can happen but only a single write?
Copy code
class DiskManagerImpl(file: File) : DiskManager {
    private val channel = AsynchronousFileChannel.open(file.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE)

    override suspend fun readPage(pageId: PageId, buffer: MemorySegment) {
        val offset = pageId * PAGE_SIZE
        val read = channel.readAsync(buffer.asByteBuffer(), offset.toLong())
        require(read == PAGE_SIZE) { "Failed to read page $pageId" }
    }

    override suspend fun writePage(pageId: PageId, buffer: MemorySegment) {
        val offset = pageId * PAGE_SIZE
        val written = channel.writeAsync(buffer.asByteBuffer(), offset.toLong())
        require(written == PAGE_SIZE) { "Failed to write page $pageId" }
    }
}
g
off the top of my head, what i would do is use 2 different dispatcher, one for reading and one for writing. Then you should be able to limit concurrency through there?
g
Ah that isn't a bad idea, like limit the write dispatcher to a single thread or whatnot?
I found this
ReadWriteMutex
example too which works with Coroutines: • https://gist.github.com/bobvawter/4ff642d5996dfccb228425909f303306
g
@Gavin Ray yeah exactly you could limit the write dispatcher to a single thread. As far as i understand the mutex will allow you to either read or write.