0

Is there a way I can allow multiple threads to perform read/write operations on a RandomAccessFile at the same time, i.e, concurrently? Do I have to use any synchronization object, or can it be done without using any synchronization?

JavaNewbie_M107
  • 2,007
  • 3
  • 21
  • 36
  • 1
    Look at http://stackoverflow.com/questions/464784/java-reentrantreadwritelocks-how-to-safely-acquire-write-lock Your best bet is to use a database like http://www.sqlite.org or other. – Romain Hippeau Mar 11 '13 at 13:57

3 Answers3

1

As Erik said, there has to be a synchronization mechanism. Otherwise this becomes the Readers/Writers problem.

If you might want to speed up things, you could have multiple reads together, and whenever you need to write, stop new read requests, let the existing request complete, get the lock, write to file, release the lock.

ReentrantReadWriteLock might help you.

karmanaut
  • 628
  • 1
  • 6
  • 17
  • 1
    If RandomFileAccess is not an absolute requirement, one could also have a look at what the java.nio.channels.FileChannel provides in terms of random access, shared/exclusive locking of (segments of) the file, and direct in memory mapping with write through. Although, just as RandomAccessFile, a FileChannel only has one position at any given point in time, keeping the need for synchronization at some point. – GPI Mar 11 '13 at 14:10
  • It was not said that the file will be accessed through only one FileChannel, file descriptor or whatever. – Ingo Mar 11 '13 at 18:38
1

A random access file behaves the same way as random access memory - it is open to all sorts of data races. Hence, as long as you're not certain that different threads work on different regions of the file, you absolutely must use synchronization.

6infinity8
  • 298
  • 4
  • 10
Ingo
  • 36,037
  • 5
  • 53
  • 100
0

You must use some sort of synchronisation method. There can only be one file position in the file. If you try concurrent access without synch, the behaviour is unpredictable at best.

Erik
  • 2,013
  • 11
  • 17