Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can multiple Java processes read the same file at the same time?

Is it possible to read the same file from two or more different processes at the same time?

I'd like to do something like this in a Java application:

final File f = new File("read-only-file");
final FileInputStream in = new FileInputStream(f);
int b;
while((b = in.read()) != null) {
    //process b
    Thread.sleep(10); //several read processes would really happen at the same time
}

No application would ever write to the file but several threads/applications need to execute the code above at the same time. Is the code above fine or do I need to use any special mechanisms in that case?

Also the solution should be platform-independent and must work on Linux like systems.

like image 820
MinecraftShamrock Avatar asked Nov 08 '14 17:11

MinecraftShamrock


1 Answers

Can multiple Java processes read the same file at the same time?

Sure they can; and ultimately, it is the role of the OS anyway to ensure that each process/thread reads at its own pace, so you need not worry about it.

Of course, you may want to share as many resources as possible between the different threads, but certainly not the I/O streams; and while we are at it, use the new file API if you use Java 7 or upper (this is 2014; it's been 3 years since Java 7 is there); File is a very inferior API compared to java.nio.file (and, in fact, compared to the file manipulation APIs of most programming languages in general).

like image 168
fge Avatar answered Oct 19 '22 03:10

fge