Reputation: 113
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.
Upvotes: 0
Views: 332
Reputation: 54128
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.
Upvotes: 1
Reputation: 533442
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.
Upvotes: 3