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
Giorgos Makris
09/10/2022, 5:13 PM
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
Gavin Ray
09/10/2022, 5:17 PM
Ah that isn't a bad idea, like limit the write dispatcher to a single thread or whatnot?
@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.