This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What exactly is "line flushing" and how does it relate to the following code?

 
Tarek Khojah
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't want to waste your time, this isn't really THAT important. My code wasn't working and now it does because of one simple change. But I don't understand what that change does. So the following is about that:

I've been struggling with writing my own (simpler) version of a client/server "program" using THIS

Very simple really, just something that would say "hi" and "hello" back and forth.

When I tried the code in the example, it worked fine. But when I wrote my own code, both the client and server programs would run, but nothing happens! When I come to close either program, I'll get an error at the while loop of the other program (Seems like both programs are just infinitely looping there).

Turns out I was omitting the bolded part of the following line when creating a PrintWriter object:

out = new PrintWriter(socket.getOutputStream(), true);

So now the code works, but why? I looked into the API, and it mentions "line flushing", but what is that exactly? I'm assuming it means erasing the contents of the writer every time I write something new! If that's the case shouldn't my code have gone the while loop at least once before getting some sort of error?
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15207
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
PrintWriter buffers the data that you write to it. After you have written a certain amount of data, or if you print a newline, or if you call flush(), it sends out the data that it has in its buffer.

It does this because it is much more efficient to send packets of data than to send the data byte by byte.

By setting the second parameter of the constructor to true, you tell PrintWriter to send out its data immediately, without buffering it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic