Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: thread-safe RandomAccessFile

After some serious googleing I found out that the RandomAccessFile-class is not thread-safe. Now I could use one semaphore to lock all reads and writes but I don't think that performs very well. In theory it should be possible to do multiple reads and one write at a time. How can I do this in Java? Is it possible at all?

Thanks!

like image 482
Folkert van Heusden Avatar asked May 21 '10 12:05

Folkert van Heusden


People also ask

What is RandomAccessFile in Java?

RandomAccessFile(File file, String mode) Creates a random access file stream to read from, and optionally to write to, the file specified by the File argument. RandomAccessFile(String name, String mode) Creates a random access file stream to read from, and optionally to write to, a file with the specified name.

What is the use of RandomAccessFile?

Java RandomAccessFile provides the facility to read and write data to a file. RandomAccessFile works with file as large array of bytes stored in the file system and a cursor using which we can move the file pointer position.

Does RandomAccessFile create a new file?

The file will be created if it doesn't exist, but the contents will not be changed if the file does exist because you are opening the file for both reading and writing.

Which method moves the file pointer in a RandomAccessFile?

The file pointer can be moved using seek() method provided by RandomAccessFile class.


2 Answers

I could use one semaphore to lock all reads and writes but I don't think that performs very well.

With respect to performance, NEVER think. ALWAYS measure.

That said, java.util.concurrent.locks.ReentrantReadWriteLock is what you are looking for.

like image 97
Kilian Foth Avatar answered Sep 22 '22 05:09

Kilian Foth


Partial locking of a file is a complex business which a lot of operating systems avoid doing. However if you insist on doing it, one way is to design your own locking mechanism object that records which parts of the file are locked. Essentially before reading or writing an object must request a lock for a specific byte range of the file. Locks are considered to clash if they overlap at all in byte range. Read and write locks are treated differently: a read can overlap with any number of read locks safely, but a write lock must overlap with no other locks, read or write. There are a lot of questions about whether to wait or abort if you can't get the lock, and whether to block reads while a write is waiting, but only you can answer them about your application.

Given the complexity of this it may be better to lock the entire file. Check to see if you get adequate performance - and don't forget you can allow multiple reads at once, as long as there are no writes.

like image 21
DJClayworth Avatar answered Sep 19 '22 05:09

DJClayworth