Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a BufferedOutputStream causes application to halt

Tags:

java

I have this line of code in my server/client pair:

BufferedOutputStream out = new BufferedOutputStream (clientSocket.getOutputStream());

It works fine, the code works well, then if I modify it to:

BufferedOutputStream out = new BufferedOutputStream (new BufferedOutputStream(clientSocket.getOutputStream()));

The execution of the application will halt where outputs are sent. I really only made that modification and am very new to streams in this manner, especially sockets.

Is there any obvious error?

like image 218
Clintonio Avatar asked Nov 29 '10 23:11

Clintonio


1 Answers

Yes, this would be consistent with the behaviour of BufferedOutputStream, which as its name suggests will buffer output before sending it.

When you write objects to the ObjectOutputStream, the bytes will be passed along to the BufferedOutputStream, which will only send them on to the socket when its buffer fills up. So your objects will be "hanging around" in the buffer, waiting to be flushed. So your outputs are not really "sent", since they haven't made it as far as the socket.

If you want to keep using BufferedOutputStream, then you may need to periodically flush() it, in order to keep things moving along. The flush() method on the ObjectOutputStream will in turn call flush() on the BufferedOutputStream, which will empty the buffer and send the objects down the pipe.

I have to ask, though, why you need to use BufferedOuputStream at all. Do you have a performance problem that needs buffering to solve? If not, then just leave it out, it adds complexity that you may not need.

like image 134
skaffman Avatar answered Oct 22 '22 10:10

skaffman