• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java flush()  RSS feed

 
Adi Sharma
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I was wondering as to why do we need to use flush() method. What is the reason behind all the bytes not reaching the destination at once. Does it has to do anything with the network???

Thanks
Aditya
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
of you write to a stream, bytes are held in a buffer with a predefined size.
only if that buffer is full or the stream is closed, the buffer is being flushed automatically..

the flush method forces the buffer to be cleared ...
 
fred rosenberger
lowercase baba
Bartender
Posts: 12562
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
often the cpu or disk drive or printer or whatever can be more efficient if it can do things in batches.

which is simpler

connect to the printer
send an 'h'
disconnect
connect to the printer
send an 'e'
disconnect
connect to the printer
send an 'l'
disconnect
connect to the printer
send an 'l'
disconnect
connect to the printer
send an 'o'
disconnect

or

connect to the printer
send an 'hello'
disconnect


but it may be easier to WRITE the characters one at a time. So, the buffer saves up the input until it gets to the 'best' size, then sends it all at once. It's possible that your last 'chunk' of data isn't enough to trigger the buffer to send the info. It'll get sent EVENTUALLY, but you may want to force it before it thinks it's ready - hence the flush.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!