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.

2
  • Using backticks (`) in your question causes the text to be formatted as code. Commented Jun 21, 2011 at 12:11
  • this may be unrelated. but why do you wanna do this?? Commented Jun 21, 2011 at 12:13

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the answer! Can I lock the BufferReader using the FileChannel lock or I would make it manually?
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. ;)
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.
I editted the question, forgotten something. Check there please!
There is no sane reason to have two classes. But even if you did it doesn't make any difference to my answer.
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.

1 Comment

+1 for a cleaner solution. That's how I would do it - read in one, process, queue to 2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.