0

I have one text file that needs to be read by two threads, but I need to make the reading sequentially. Example: Thread 1 gets the lock and read first line, lock is free. Thread 2 gets the lock and read line 2, and so goes on. I was thinking in sharing the same buffer reader or something like that, but I'm not so sure about it. Thanks in advance!

EDITED

Will be 2 classes each one with a thread. Those 2 classes will read the same file.

Samth
  • 113
  • 1
  • 1
  • 5

2 Answers2

3

You can lock the BufferReader as you say.

I would warn you that the performance is likely to be worse than using just one thread. However you can do it as an exercise.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Thanks for the answer! Can I lock the BufferReader using the `FileChannel` lock or I would make it manually? – Samth Jun 21 '11 at 12:15
  • You can use any object which shared between the threads. The BufferedReader or FileChannel has to be shared for this to work. You did read my warning that it was probably pointless. ;) – Peter Lawrey Jun 21 '11 at 12:21
  • The simplest approach is to create the shared object(s) e.g. as final local variables, and then create the two threads so they both have access to the object e.g. as an anonymous Runnable class. – Peter Lawrey Jun 21 '11 at 13:38
  • I editted the question, forgotten something. Check there please! – Samth Jun 21 '11 at 13:45
  • There is no sane reason to have two classes. But even if you did it doesn't make any difference to my answer. – Peter Lawrey Jun 21 '11 at 13:52
1

It would probably be more performant to read the file line by line in one thread, and pass the resulting input lines to a thread pool via a queue such as ConcurrentLinkedQueue, if you want to guarantee order at least of start of processing of the files lines. Much simpler to implement, and no contention on whatever class you use to read the file.

Unless there's some cast-iron reason why you need the reading to happen local to each thread, I'd avoid sharing the file like this.

Steve Townsend
  • 53,498
  • 9
  • 91
  • 140