Search code examples
javaiorandom-access

Using Multiple Threads to write in single file


Can i use multiple threads to write in RandomAccessFile in Java ?

I know RandomAccessFiles allows to read & write at any position.

I want to create n portions of above File and let each thread to write contents in a particular portion.

will it improve IO performance?

Eager to hear soon......


Solution

  • You can open the file twice with the proper sharing specified, having two RandomAccessFile objects pointing to the same file. The OS will manage properly if you're careful not to write and read the same location twice (the OS will handle it then, too, but you'll get unexpected results).

    However, it will not improve your I/O performance - CPU is almost never the bottleneck when it comes to I/O. What is it you're trying to achieve?