Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

java - Sockets: BufferedOutputStream or just OutputStream?

In order to get the fastest transfer speeds over TCP in Java, which is better:

Option A:

InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();

Option B:

BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());

I've read that performance takes a hit when writing over 8 KiB to OutputStream, it was recommended that it'd be written to it in small chunks not pver 8 KiB at a time. 8 KiB is the default buffer size of a BufferedOutputStream.

However I've also read that when transfering data over the net it's good to flush out the bytes as quickly as possible. Meaning that using a buffer and writing in small chunks adds a unneeded overhead.

So, option A or option B? Which works best?

Right now I'm guessing option A gives highest transfer speeds while consuming a lot more CPU than option B. Option B might be better since it doesn't go that much slower but saves a lot of CPU.

--

Bonus question: Is it a good idea to touch the TCP window size? For example by setting it to 64 KiB:

socket.setReceiveBufferSize(65536);
socket.setSendBufferSize(65536);

I tried setting it to 128 KiB on a test machine since I read that it could increase speeds but when the server got a couple of connections the CPU were at 100% instead of ~2% like when I left it alone. I guess 128 KiB is way too high unless you've got a good server that can handle that rush in traffic, but is it smart to set it to something like 32 KiB? I think the default was 8 KiB there for me.

("socket" is "java.net.Socket")

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I don't know where you read all that nonsense but it is completely back to front. The more you write at a time to a TCP connection the better, and the more you read from it at a time ditto. I would always use a buffered stream, reader, or writer between the application and the socket streams. There are some cases like SSL where directly writing a byte at a time can cause a 40x data explosion.

Is it a good idea to touch the TCP window size? For example by setting it to 64 KiB

You can't 'touch the TCP window size'. You can increase its maximum value via the APIs you mention, and that is indeed a good idea.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...