views:

68

answers:

2

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 ?

+3  A: 

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.

Yan Cheng CHEOK
thank you very much !! that's exactly what i wanted. it's better than read/write from DataBase or file.
mohamida
A: 

I think it is possible using java NIO libraries

Suresh S
I don't think it is Suresh, but I'm happy to be corrected if you show how to do it.
Nick Fortescue
@Nick using selectors for each thread and synchronising on them is possible.
Suresh S