8

Here's the scenario:

  • ThreadA is going to read from some socket, and write data to "MyFile.txt"
  • ThreadB is going to read "MyFile", and when it reaches the end, it will loops until new data are available in MyFile (because i don't want to re-open "MyFile.txt", and lose the time so i reach the position from where i was..).

Is it possible to do such a thing ?

If not, is there another way to do such a thing ?

mohamida
  • 804
  • 2
  • 11
  • 25
  • possible duplicate of [How do I use Java to read from a file that is actively being written?](http://stackoverflow.com/questions/4149/how-do-i-use-java-to-read-from-a-file-that-is-actively-being-written) – Nick Fortescue Oct 19 '10 at 07:57
  • I've added a link to a question which is a duplicate of this one. But in passing, have you seen RandomAccessFile? You don't need to go through an entire file again to read from a particular position – Nick Fortescue Oct 19 '10 at 07:58

1 Answers1

13

The problem you mention is a famous Producer Consumer Problem

Common solution to this is to use BlockingQueue

An example of real world usage is in AjaxYahooSearchEngineMonitor

What Thread A does is, it will submit a string to queue, and then return immediately.

What Thread B does is, it will pick up the item from queue one by one, and process them. When there is no item in the queue, Thread B will just wait there. See line 83 of the source code.

Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875
  • thank you very much !! that's exactly what i wanted. it's better than read/write from DataBase or file. – mohamida Oct 19 '10 at 09:16