0

I have a java program which has two threads : a read thread and a write thread. The write thread takes instructions from user to be done and writes it in the text file. The read thread reads the instructions in the text file and executes them. If an instruction is successfully executed it is to be deleted from text file so that it is not executed again.

What is the best way to achieve this?

I am thinking of using append during write thread and then use a temp file to create a new text file during read thread so that I can remove the instructions that have been executed.

Do I need to use some type of locks so that data remains synchronized during read/write operations. Also a temp file approach is fine or should I use random access?

Thanks

ak111in
  • 107
  • 2
  • 11
  • You don't. There is no guarantee in one way or the other. All the more so that depending on the encoding used by a text file, a same character can lead to more than one byte being written to a file. Use a different method. – fge Jul 17 '15 at 17:56
  • Possible duplicate of http://stackoverflow.com/questions/3966229/is-it-possible-to-read-and-write-in-file-at-the-same-time http://stackoverflow.com/questions/8483034/how-to-read-and-write-data-into-same-file-simultaneously – SatyaTNV Jul 17 '15 at 17:59
  • 1
    If you have two threads in your program, just use a [`BlockingQueue`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/BlockingQueue.html), not a file. If the purpose of the exercise is to use a file, then you will need to use locks so the two threads access (and modify) the file one after the other. They can not be concurrent. – dsh Jul 17 '15 at 17:59

0 Answers0