When using object streams over sockets, I have to flush the streams after each write operation. In fact I even have to flush the output stream soon after creation. Is there a way out of this?

Tim Rohaly

The ObjectOutput interface provides a flush() method, implying that implementations are allowed to buffer the output. The semantics of buffered output are such that if you want the data to be sent immediately, you need to flush the buffer (the FAQ at http://www.jguru.com/jguru/faq/view.jsp?EID=32701 talks about this as well).

It seems you are expecting to be able to read the data on the other end of the stream immediately after it is written; as you have found out, the only way to ensure that the data is sent over the socket immediately is to flush the buffer. The alternatives, setting the buffer size to be very small or turning off buffering entirely, are not available with socket output streams.

The other problem you mention, having to flush the buffer after creation of the ObjectOutputStream, is similar. Instantiating an ObjectOutputStream causes the stream header information to be written to the underlying (buffered) stream. On the other end, instantiating ObjectInputStream causes this header information to be read from the stream. If the output stream buffer hasn't been flushed, then the ObjectInputStream constructor will block until it can read the header information. Hence, when using buffered I/O, it is usually a good idea to flush the ObjectOutputStream right after creation. There is no other way to do this.

0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.