File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes about Threads: Redirecting Output to a file... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "about Threads: Redirecting Output to a file..." Watch "about Threads: Redirecting Output to a file..." New topic

about Threads: Redirecting Output to a file...

Panos Liaskos
Ranch Hand

Joined: Jul 28, 2003
Posts: 34
In multithreaded code launching a class as e.g. java myClass, the messed order in which Threads execute is pretty much obvious.
However, If you use the output redirection character e.g. java myClass > output.txt then the content of the .txt file is, sometimes, a bit confusing about what really happened.
To be more specific, if you run the K/B 9.2 Exercise Answer (pg 555) without lines 9 and 18 as: java InSync > Output.txt you get the same output as the one you get if the block code was synchronized.
So, what is really happening with the > character?
Thanks for any help.
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
I am able to replicate your experience.
My best educated guess is that writing text to a file is actually a lot faster than displaying text to a console.
So, the run method of each thread executes very quickly when outputting to the text file. So fast that each running thread has completed its task before the next thread gets a turn, and before the main thread terminates.
But when output is being directed to the console, the time taken to display each character is time that might have otherwise been spent outputting characters, so not all threads complete their task and not every character gets output before the main thread terminates.

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
I agree. Here's the link:
subject: about Threads: Redirecting Output to a file...
It's not a secret anymore!