Skip to content

Commit d135bd3

Browse files
committed
added Zero Bytes Copy page
1 parent cbb5716 commit d135bd3

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

src/site/apt/zero-bytes-copy.apt

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
------
2+
Async Http Client - Zero Bytes Copy
3+
------
4+
Jeanfrancois Arcand
5+
------
6+
2012
7+
8+
Zero Bytes Copy
9+
10+
When uploading or downloading bytes, it is important to try to avoid buffering bytes in memory.
11+
12+
* Upload
13+
14+
On the upload side, the mechanism is enabled by default when setting the <<<Request>>>'s body to a File:
15+
16+
+-----+
17+
AsyncHttpClient client = new AsyncHttpClient();
18+
File file = new File("file.avi");
19+
Future f = client.preparePut("http://localhost").setBody(file).execute();
20+
+-----+
21+
22+
If you can't use a File, the recommended way is to use a <<<BodyGenerator>>>. It is strongly recommended to avoid
23+
using <<<InputStream>>> as the library will unfortunately buffer the entire content in memory in order to set the
24+
<<<content-lenght>>>, which can cause out of memory error.
25+
26+
* Download
27+
28+
On the download side, you can use the <<<HttpResponseBodyPart.writeTo>>> to avoid loading bytes in memory and
29+
unnecessary copy:
30+
31+
+-----+
32+
AsyncHttpClient client = new AsyncHttpClient();
33+
File tmp = new File("zeroCopy.txt");
34+
final FileOutputStream stream = new FileOutputStream(tmp);
35+
Future f = client.prepareGet("http://localhost/largefile.avi").execute(new AsyncHandler() {
36+
public void onThrowable(Throwable t) { }
37+
38+
public STATE onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
39+
bodyPart.writeTo(stream);
40+
return STATE.CONTINUE;
41+
}
42+
43+
{ .... } });
44+
Response resp = f.get();
45+
+-----+

0 commit comments

Comments
 (0)