If a simple mutex on the entire file is going to give you a performance bottleneck, and RandomAccessFile
is not thread-safe without a mutex, then you need to look at alternatives to RandomAccessFile
.
One alternative is to map the file into memory as a MappedBuffer
and use slices of the buffer to allow different threads to access the file without interfering with each other. Single writer / multiple reader locking at the granularity of the entire would be easy to implement. You could also go further and implement concurrent reading and writing of non-overlapping sections of the file, but that would be more complicated.
I would not be surprised to hear that someone, somewhere has already implemented this as a reusable library.