0

If I'm trying to read through a file using a Java BufferedReader. Would it be faster to use multihreading to get the next piece of the buffer into Ram while I'm doing operations on the previous piece of the buffer?

I know reading is especially slow so the reading thread still would probably get beat by the main thread and the program could end up waiting anyway but with a few more threads running is there any reason that this wouldn't speed up a read?

Malt
  • 28,965
  • 9
  • 65
  • 105
  • No, why? Is your hard disk multithreaded? You can read millions of lines per second with `BufferedReader`. Isn't that sufficient? – user207421 Mar 25 '19 at 09:18

1 Answers1

1

Probably not. (But if you have time, I welcome you to try and compare.)

As you're saying yourself, the processing thread will likely just spend most of its time waiting on the reading thread. And -- more importantly -- it's likely you're complicating your software for very little gain (see "premature optimisation").

This doesn't mean the idea is bad. Let's suppose your computation is very computationally expensive and the place you're reading from is very slow (e.g., dial-up modem). Then yes, you could benefit from splitting the reading and doing processing in different threads, so neither has to pause for the other as much as possible. You're still bounded by the slowest of threads and given a lot of data one of the threads will eventually have to wait for the other.

Note on nomenclature: I made assumption that instead of "hyperthreading" which is a market name for a processor hardware feature, you really meant "multithreading" which is a programming concept.

JohnLM
  • 195
  • 3
  • 8
  • Sorry wouldn't slower reading actually make this approach effectively worse? If reading takes longer relative to the calculations more time is going to be spent waiting for reading regardless if I *multithread (thanks) or not? I would think when reading thread time gets closer to the other time it would be more worth it because you could potentially completely nullify the reading time. – hackerman9000 Mar 25 '19 at 09:38
  • @hackerman9000 The most gain is when your threads are working at comparable speed. Of course your process is still bounded by the slowest of the threads. – JohnLM Mar 25 '19 at 20:14
  • @hackerman9000 Yes, it's true, you may nullify reading time if you process data in parallel but if the reading is _a lot_ faster than processing, the overall gain can be negligible. – JohnLM Mar 25 '19 at 20:24