• Post Reply Bookmark Topic Watch Topic
  • New Topic

read a file while it is being written

 
Raj Ohadi
Ranch Hand
Posts: 316
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If there is a file whose content is "hello world." Thread A tries to write to the file and change the content into "how are you ?", while thread A is in the middle of writing to the file, thread B tries to read this file. what will thread B get ?

1. thread B will still read "hello world" since thread A is not done yet.
2. thread B will get "FileNotFoundException"
3. thread B will get "IOException"
4. other result

Above is NOT a test question. Just my guess. What is the answer ??
 
Joe Ess
Bartender
Posts: 9362
11
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Raj Ohadi:
What is the answer ??


Why don't you write a test case and try it?
You should be able to code up such a test in a few minutes.
 
Raj Ohadi
Ranch Hand
Posts: 316
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Joe Ess:


Why don't you write a test case and try it?
You should be able to code up such a test in a few minutes.


First, I am not familiar with multi-threading programming. Secondly, I don't know how to "guarantee" that when the 2nd thread starts reading, the 1st thread is still in the middle of writing (the 1st can't finish it, if it finishes writing it is not what I want to test).

I am not able to do this within few minutes..
 
Joe Ess
Bartender
Posts: 9362
11
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This would be a good time to get familiar with threads, since you have a particular problem in mind. A good place to start would be the Java Tutorial on Threads.
As for your original question, while two threads can simultaneously read/write from/to the same file (Unix pipes are implemented this way), and it is unlikely that file reads and writes are atomic (assigning longs and floats are not atomic), I would think it very unlikely that the VM, OS and hardware would be in such a state where a write invocation would block, one thread would yield, another thread would start and complete a read invocation. There are so many things happening the results may be different from one run of the program to the next. One certainly could not rely on such a set up to behave consistently.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!