Timing issues with PrintStreams - java

I'm using eclipse IDE, and sometimes, depending on the code, System.err output is printed before than System.out's. For instance:
public static void main(String[] args) {
System.out.println("Regular text"); //1
System.err.println("Error text"); //2
}
With that code, everything is fine. 2 is printed after 1. However, adding some extra system.out sentences reverses the order:
public static void main(String[] args) {
System.out.println("Regular text"); //1
System.err.println("Error text"); //2
//Additional printing stuff
for(String s = "a";s.length() < 200; s = s.concat("" + (char)(s.charAt(s.length()-1)+ 1))){
System.out.println(s);
}
}
1 is printed after 2.
How is this possible?

stderr and stdout are 2 different streams, and normally will be printed when flushed. I would expect some buffering to take place and this would affect flushing. Consequently the quantity of data in each stream will affect the flushing and the output.

On some OSes (*nix in particular), the standard output stream is buffered -- that is, whatever gets sent to it might sit around a bit before being sent to the terminal/screen. Standard error, however, often is not buffered, or is auto-flushed after each output.
System.out and System.err are just Java's objects to represent those two streams, and thus, tend to behave as they would on the host platform. But i'm not aware of anything that specifically says they have to.

They are separate streams each with their own buffers. You write to a stream which is then "copied" or written out to the console.
You should find that calling
System.out.flush()
System.err.flush()
will flush the streams to the actual device (the Eclipse console) and bring some semblance of order.

Related

Multiple quotes cause PipedOutputStream/OutputStreamWriter to fail

I stumbled over a very strange behavior with the PipedOutputStream when I was trying to copy an OutputStream to an InputStream. See also How to write an nt:file programmatically
Here is a small unit test method:
#Test
public void pipeTest() {
PipedInputStream pin = null;
try {
pin = new PipedInputStream();
PipedOutputStream pout = new PipedOutputStream(pin);
OutputStreamWriter writer = new OutputStreamWriter(pout);
for (int i = 0; i < 100; i++) {
writer.write("\"Test\";" + i + "\n");
// writer.write("\"Test\";" + "\"" + i + "\"\n");
}
writer.close();
pout.close();
System.out.print(IOUtils.toString(pin));
} catch (IOException e) {
System.out.print(e);
} finally {
IOUtils.closeQuietly(pin);
}
}
This works well and prints out 100 rows. If you uncomment the second write statement and comment out the first, writer.close() gets stuck and never finishes. It seems to have problem with the second set of quotes \".
Has anyone and idea why this is the case and how to circumvent it?
This has nothing to do with the quotes - and everything to do with how much data you're writing. To demonstrate this, you can get rid of the writer and the loop entirely, and just use:
pout.write(new byte[1024]);
Or keep your existing code, but see that this works (because it writes 1000 bytes):
writer.write("0123456789");
but this doesn't (because it tries to write 1100 bytes):
writer.write("0123456789X");
That works - but if you change it to 1025, it'll hang forever... because the internal buffer is 1024 bytes long by default, and nothing's consuming the stream. (You're not reading from pin until you've finished writing.) As nothing is consuming any of the first 1024 bytes, there's nowhere to put the 1025th byte, so write blocks until there is space.
You could:
Change the pipe size when you construct the PipedInputStream, so it's got a bigger buffer
Read from the pipe while you're writing - e.g. in a separate thread.
A PipedInputStream has an internal buffer. By default the buffer is 1024 bytes, but you can pass a different size to the constructor of PipedInputStream.
When the buffer is full, a write the the PipedOutputStream that's associated with the PipedInputStream blocks until you have read enough data from the latter, so that there is space in the buffer.
Your problem is unrelated to the double quotes itself; it's just that you write more data when you add the double quotes.
You should only use the piped stream in multi-threaded code (in which one thread writes to the piped output stream, and another thread reads from the piped input stream), to avoid this possible deadlock.
The Javadoc for PipedInputStream has a clear warning about this:
Attempting to use both objects from a single thread is not
recommended, as it may deadlock the thread.

Error output stream is concurrent with standard output stream when printing in Java

When this code gets executed, it produces scrambled outputs with no particular order between System.out.print() and System.err.print(). Why is that so?
for (int i = 0; i < 100; i++) {
System.out.print(i+" ");
System.err.print(i+"+");
}
Why is the standard error output stream is concurrent with standard output stream when printing in Java?
System.out and System.err are two different streams and so, they work at different times. The problem you're experiencing here is because in console applications both streams are flushed to the same output buffer, which is the console. Each stream can flush at different time, the console buffer will care about the synchronization for you, but this leads to unpredictable results.
If you want/need to have a single and better managed output for both streams, use a logger library like log4j2 or logback, that already solves these problems.

Race between System.out and System.err in java [duplicate]

This question already has answers here:
System.out.println and System.err.println out of order
(7 answers)
Closed 9 years ago.
Please consider this java code:
public class CMain {
public static void main(String[] args){
for (int i = 0; i < 10; i++) {
System.out.println("A");
System.err.println("B");
}
}
}
By a quick look at the code, some of us may think the output has to be the print of As and Bs alternatively. However is not! It is a random appearance of 10 A characters and 10 B ones. Something like this:
Why is that? and what is the solution for it so that the As and Bs gets displayed alternatively ( A B A B A B ...)
Before I ask this question, I checked several other similar questions for solution and non worked for my case! I have brought some of them here:
Synchronization and System.out.println
Java: synchronizing standard out and standard error
Java: System.out.println and System.err.println out of order
PS. I am using Eclipse as my IDE
Why does this happen?
This is because out and err are two different output streams. However, both of them print on console. So you do not see them as different streams. Moreover, when you do out.println(), it is not guaranteed that you will see the output on the console as soon as the statement gets executed. Instead, the strings are usually(depends on the system) stored in an output buffer (if you will) which is processed later by the system to put the output from the buffer onto the screen.
Solution :(
Although, as Eng.Fouad pointed out that you can use setOut(System.err) or setErr(System.out) to make them ordered, I would still not suggest doing that when you are actually putting this in an application (only use it for debugging purposes).
What the proposed solution does is that it will end up using only one stream for both the standard output and the standard error, which I do not think is a good thing to do.
They are different OutputStreams. If you really need to guarantee the order of printing them, use:
System.setErr(System.out);
or
System.setOut(System.err);
Since there are two separate streams, the output you are giving is possible.

difference between System.out.println() and System.err.println()

What is the difference between System.out.println() and System.err.println() in Java?
In Java System.out.println() will print to the standard out of the system you are using. On the other hand, System.err.println() will print to the standard error.
If you are using a simple Java console application, both outputs will be the same (the command line or console) but you can reconfigure the streams so that for example, System.out still prints to the console but System.err writes to a file.
Also, IDEs like Eclipse show System.err in red text and System.out in black text by default.
System.out is "standard output" (stdout) and System.err is "error output" (stderr). Along with System.in (stdin), these are the three standard I/O streams in the Unix model. Most modern programming environments (C, Perl, etc.) support this model.
The standard output stream is used to print output from "normal operations" of the program, while the error stream is for "error messages". These need to be separate -- though in most cases they appear on the same console.
Suppose you have a simple program where you enter a phone number and it prints out the person who has that number. If you enter an invalid number, the program should inform you of that error, but it shouldn't do that as the answer: If you enter "999-ABC-4567" and the program prints an error message "Not a valid number", that doesn't mean there is a person named "Not a valid number" whose number is 999-ABC-4567. So it prints out nothing to the standard output, and the message "Not a valid number" is printed to the error output.
You can set up the execution environment to distinguish between the two streams, for example, make the standard output print to the screen and error output print to a file.
Those commands use different output streams. By default both messages will be printed on console but it's possible for example to redirect one or both of these to a file.
java MyApp 2>errors.txt
This will redirect System.err to errors.txt file.
System.out's main purpose is giving standard output.
System.err's main purpose is giving standard error.
Look at these
http://www.devx.com/tips/Tip/14698
http://wiki.eclipse.org/FAQ_Where_does_System.out_and_System.err_output_go%3F
System.out.println("wassup"); refers to when you have to output a certain result pertaining to the proper input given by the user whereas System.err.println("duh, that's wrong); is a reference to show that the input provided is wrong or there is some other error.
Most of the IDEs show this in red color (System.err.print).
this answer most probably help you it is so much easy
System.err and System.out both are the same both are defined in System class as reference variable of PrintStream class as
public final static PrintStream out = null;
and
public final static PrintStream err = null;
means both are ref. variable of PrintStream class.
normally System.err is used for printing an error messages, which increase the redability for the programmer.
A minor difference comes in both when we are working with Redirection operator.
It's worth noting that an OS has one queue for both System.err and System.out. Consider the following code:
public class PrintQueue {
public static void main(String[] args) {
for(int i = 0; i < 100; i++) {
System.out.println("out");
System.err.println("err");
}
}
}
If you compile and run the program, you will see that the order of outputs in console is mixed up.
An OS will remain right order if you work either with System.out or System.err only. But it can randomly choose what to print next to console, if you use both of these.
Even in this code snippet you can see that the order is mixed up sometimes:
public class PrintQueue {
public static void main(String[] args) {
System.out.println("out");
System.err.println("err");
}
}

try-catch block in Java - execution statements in catch code

I have a question about the order of the execution of statements in a catch block in Java.
when I run the following class Test1 (see below), I expect to have as output first Hi!, then the result of the e.printStackTrace(); statement, and then Bye!. However, I never get this order. Please, look at the outputs, which I have pasted below.
public class Test1 {
public static void calculate() {
try {
int h = 5/0;
} catch (ArithmeticException e) {
System.out.println("Hi!");
e.printStackTrace();
}
System.out.println("Bye!");
}
public static void main(String[] args) {
calculate();
}
}
Output1:
Hi!
Bye!
java.lang.ArithmeticException: / by zero
at Test1.calculate(Test1.java:6)
at Test1.main(Test1.java:15)
Output2:
java.lang.ArithmeticException: / by zero
at Test1.calculate(Test1.java:6)
at Test1.main(Test1.java:15)
Hi!
Bye!
I have two questions:
1.) The more important question: Why I always have Hi! and Bye! printed always one after the other, even though mye.printStackTrace() in the code is between them?
2.) Why sometimes I have the output of the statement e.printStackTrace() before Hi!, and sometimes after Bye! ? I have run the program many times and I cannot understand under what circumstances I get one or the other print.
Thank you.
I am using Java 6, and Eclipse (Ganymed).
Exception.printStackTrace() prints to System.err whereas "Hi!" and "Bye!" are on System.out. If you run your program on a regular console, they eventually end up on the screen, but the order may be out. If you are running the program through an IDE (e.g. NetBeans), the streams will probably be color-coded so you can easily distinguish them.
You print "Hi!" and "Bye!" to System.out (i.e. stdout), while the stack trace is printed to System.err (i.e. stderr). The order in which they are printed is determined by when the two buffers are flushed.
It could be a timing issue. Println writes to standard out, while printStackTrace might be hooked up to standard error. Then it's just a matter of which buffer gets flushed first.
A1 - e.printStackTrace() prints to System.err and not System.out, so different streams, different print order.
try adding System.out.flush() after every print (printStackTrace included).

Categories

Resources