4

Suppose I have two threads (threadA and threadB), where threadA is reading from a file et threadB is writing to this same file, here are the two methods :

// Thread A reads
java.nio.file.Files.readAllBytes(Path.get("test.txt"));

// Thread B writes
java.nio.file.Files.write(Paths.get("test.txt"), bytes);

What will happen if both threads run at the same time ?

If threadA begins to read, then threadB writes to the file (threadA hasn't finished yet to read), Will threadA read the original file (before the modification of threadB) or the modified file or will it throw an exception ?

Olivier Boissé
  • 15,834
  • 6
  • 38
  • 56
  • 3
    Try it and see; because it depends on your file system. Try locking the file for read and writes respectively, and see how the behavior changes. – Elliott Frisch Dec 29 '19 at 17:09
  • the problem is that it's really difficult to test because both read and write should occur at the very same time. – Olivier Boissé Dec 29 '19 at 17:14
  • 3
    Start one hundred read threads (read the file); start five write threads (append one line, or character if you prefer, to the file). You should see results quickly. – Elliott Frisch Dec 29 '19 at 17:26
  • 1
    @OlivierBoissé Why should read and write occur at the very same time? What are you designing which requires that you want to use this approach? And how do you expect your application will work by writing and saving at the same time? What do you get by designing your application like that? You are creating a race-condition on purpose, which you don't want to have in the first place. – Progman Dec 29 '19 at 21:02
  • I have a batch which call a webservice and store the result into a file once a day. This file is usefull to display some informations to a web page (let's call it the homepage). So when a client goes to the homepage, the file is read and if it occurs at the very same time that the batch is running, I just wonder what will happen in this case ? I expect that no exception will be thrown, I don't matter if the file read is the original or the one updated by the batch – Olivier Boissé Dec 29 '19 at 21:14

1 Answers1

0

It is not an answer to your question "what will happen", but...

Writing the result of your batch into a result.file and "processing" it should be handled each by a seperate handler. Take a look at the directory watch service Watching a Directory for Changes After the new result.file.yyy-mm-dd (e.g.) is written, or the file is modified, it should be parsed and the webcontent should be prepared. Otherwise it is parsed each time someone visits the page - that is not that elegant I think. With the help of a lock-mechanism like synchronized the 'might-be'-moment can be avoided.

SvenJu
  • 31
  • 1
  • 5