In this program, the third string never gets printed. Why?
(This Java program was run on Eclipse Indigo on Ubuntu 10.10.)
import java.io.PrintWriter;
public class Tester
{
static void nested()
{
PrintWriter object2 = new PrintWriter(System.out, true);
object2.println("second");
object2.close(); // delete this line to make all strings print
}
public static void main(String[] args)
{
PrintWriter object1 = new PrintWriter(System.out, true);
object1.println("first");
Tester.nested();
object1.println("third");
object1.close();
}
}
By closing the nested
PrintWriter, you also close the embeddedSystem.outstream, which seemingly prevents further writes to it (although I would expect an exception really instead of swallowing output).So the entire problem can be reduced to:
This too doesn’t print anymore after “first”, but also doesn’t throw an exception. A very quick debugging session shows there’s a call to a Sun native function, which is a little harder to debug into.
Update*
This is the culprit:
System.outis of typejava.io.PrintStreamand it contains the following lovely method:The
ensureOpen()method indeed throws an exception, but it’s swallowed here and thetroubleflag is set (a well known anti-pattern). This thus silently ignores further writes to the closed stream.