Loop Printing
The task of sending a string to a file or the display is an I/O-bound task. Using multithreaded techniques on a loop of output does not make sense. Since the operation is I/O-bound, the threads will spend most of their time waiting, and there is little difference in having one processor or twelve processors available to run waiting threads. Furthermore, the order of the output is important. Data that is written to a file or the display will eventually be read by a person or another application. The output must look the same whether the calculation is done as a single-threaded or multithreaded application.
However, what if the printing portion of the loop is small when
compared with the mathematical calculation? If enough of the loop is
CPU intensive, it might be silly to abandon an attempt at
parallelizing the loop just because it contains a
println()
method call. The only problem that
needs to be solved is the ordering of the output. This can be done by
a two-step printing process. Instead of printing directly to the
display or file, the application can print to a virtual, memory-based
display along with an index that is used to order the output. When
the processing of the loop has completed, the output can then be sent
to the display or file, using the index information to ensure that
the data is sent in the correct order.
Let’s reexamine our SinTable loop:
public synchronized float[] getValues() { if (lookupValues == null) { for (int i = 0; i < (360*100); i++) ...
Get Java Threads, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.