-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjava-zero-copy.html
820 lines (355 loc) · 35.4 KB
/
java-zero-copy.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
<!DOCTYPE html>
<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">
<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />
<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />
<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />
<link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">
<link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">
<link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">
<link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">
<meta name="keywords" content="java,linux,zero-copy," />
<link rel="alternate" href="/atom.xml" title="个人博客" type="application/atom+xml" />
<meta name="description" content="本篇内容主要翻译自Efficient data transfer through zero copy,包括有些自己的思考 java zero copy很多网页应用有大量的静态内容,针对这些静态内容主要的处理逻辑就是从磁盘读取数据,然后将数据写入到响应的socket中。这项工作应该需要较少的CPU资源。但是有时候并不是。内核从磁盘读取数据,然后将数据拷贝到应用中。之后应用将数据写入到内核,然后推">
<meta property="og:type" content="article">
<meta property="og:title" content="java-zero-copy">
<meta property="og:url" content="https://lightnine/github.io/java-zero-copy.html">
<meta property="og:site_name" content="个人博客">
<meta property="og:description" content="本篇内容主要翻译自Efficient data transfer through zero copy,包括有些自己的思考 java zero copy很多网页应用有大量的静态内容,针对这些静态内容主要的处理逻辑就是从磁盘读取数据,然后将数据写入到响应的socket中。这项工作应该需要较少的CPU资源。但是有时候并不是。内核从磁盘读取数据,然后将数据拷贝到应用中。之后应用将数据写入到内核,然后推">
<meta property="og:locale">
<meta property="og:image" content="https://lightnine/java-zero-copy/figure1.gif">
<meta property="og:image" content="https://lightnine/java-zero-copy/figure2.gif">
<meta property="og:image" content="https://lightnine/java-zero-copy/figure3.gif">
<meta property="og:image" content="https://lightnine/java-zero-copy/figure4.gif">
<meta property="og:image" content="https://lightnine/java-zero-copy/figure5.gif">
<meta property="article:published_time" content="2023-12-04T03:17:19.000Z">
<meta property="article:modified_time" content="2024-12-12T03:52:34.292Z">
<meta property="article:author" content="liang">
<meta property="article:tag" content="java">
<meta property="article:tag" content="linux">
<meta property="article:tag" content="zero-copy">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://lightnine/java-zero-copy/figure1.gif">
<script type="text/javascript" id="hexo.configurations">
var NexT = window.NexT || {};
var CONFIG = {
root: '',
scheme: 'Muse',
version: '5.1.4',
sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
fancybox: true,
tabs: true,
motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
duoshuo: {
userId: '0',
author: '博主'
},
algolia: {
applicationID: '',
apiKey: '',
indexName: '',
hits: {"per_page":10},
labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
}
};
</script>
<link rel="canonical" href="https://lightnine/github.io/java-zero-copy.html"/>
<title>java-zero-copy | 个人博客</title>
<meta name="generator" content="Hexo 7.0.0"></head>
<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
<div class="container sidebar-position-left page-post-detail">
<div class="headband"></div>
<header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
<div class="header-inner"><div class="site-brand-wrapper">
<div class="site-meta ">
<div class="custom-logo-site-title">
<a href="/" class="brand" rel="start">
<span class="logo-line-before"><i></i></span>
<span class="site-title">个人博客</span>
<span class="logo-line-after"><i></i></span>
</a>
</div>
<p class="site-subtitle"></p>
</div>
<div class="site-nav-toggle">
<button>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
</button>
</div>
</div>
<nav class="site-nav">
<ul id="menu" class="menu">
<li class="menu-item menu-item-home">
<a href="/" rel="section">
<i class="menu-item-icon fa fa-fw fa-home"></i> <br />
首页
</a>
</li>
<li class="menu-item menu-item-about">
<a href="/about/" rel="section">
<i class="menu-item-icon fa fa-fw fa-user"></i> <br />
关于
</a>
</li>
<li class="menu-item menu-item-tags">
<a href="/tags/" rel="section">
<i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
标签
</a>
</li>
<li class="menu-item menu-item-categories">
<a href="/categories/" rel="section">
<i class="menu-item-icon fa fa-fw fa-th"></i> <br />
分类
</a>
</li>
<li class="menu-item menu-item-archives">
<a href="/archives/" rel="section">
<i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
归档
</a>
</li>
</ul>
</nav>
</div>
</header>
<main id="main" class="main">
<div class="main-inner">
<div class="content-wrap">
<div id="content" class="content">
<div id="posts" class="posts-expand">
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<div class="post-block">
<link itemprop="mainEntityOfPage" href="https://lightnine/github.io/java-zero-copy.html">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="">
<meta itemprop="description" content="">
<meta itemprop="image" content="/images/avatar.gif">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="个人博客">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">java-zero-copy</h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">发表于</span>
<time title="创建于" itemprop="dateCreated datePublished" datetime="2023-12-04T11:17:19+08:00">
2023-12-04
</time>
</span>
<span class="post-category" >
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-folder-o"></i>
</span>
<span class="post-meta-item-text">分类于</span>
<span itemprop="about" itemscope itemtype="http://schema.org/Thing">
<a href="/categories/linux/" itemprop="url" rel="index">
<span itemprop="name">linux</span>
</a>
</span>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<blockquote>
<p>本篇内容主要翻译自<a href="https://developer.ibm.com/articles/j-zerocopy/">Efficient data transfer through zero copy</a>,包括有些自己的思考</p>
</blockquote>
<h1 id="java-zero-copy"><a href="#java-zero-copy" class="headerlink" title="java zero copy"></a>java zero copy</h1><p>很多网页应用有大量的静态内容,针对这些静态内容主要的处理逻辑就是从磁盘读取数据,然后将数据写入到响应的socket中。这项工作应该需要较少的CPU资源。但是有时候并不是。内核从磁盘读取数据,然后将数据拷贝到应用中。之后应用将数据写入到内核,然后推送到socket中。实际上,应用程序在这里扮演了一个无效率的中间层,既将数据从磁盘写入到socket。<br>每一次当数据在用户空间和内核空间转换时,数据都会被拷贝,而这会消耗cpu cycles以及内存带宽。幸运的是,我们可以采用zero copy技术来避免内核和应用程序之间的数据拷贝。应用程序使用zero copy技术来请求内核直接将数据从磁盘文件拷贝到socket中,而不需要经过应用程序。zero copy技术能够极大的提升应用程序性能并且减少内核空间和用户空间之间的切换。<br>Java中使用<code>java.nio.channels.FileChannel</code>中的<code>transferTo()</code>方法在linux和Unix系统重实现zero copy。使用<code>transferTo()</code>方法能够直接将字节数据从一个channel写入到另一个channel中,而数据不需要经过应用程序。本篇文章首先展示使用传统的拷贝方法消耗的资源,然后展示使用zero copy获得的性能提升。</p>
<h2 id="数据传输-传统方法"><a href="#数据传输-传统方法" class="headerlink" title="数据传输:传统方法"></a>数据传输:传统方法</h2><p>想想一个简单的场景,从一个文件读取数据,然后将数据通过网络写入到另一个程序中。核心操作如下所示。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">File.read(fileDesc, buf, len);</span><br><span class="line">Socket.send(socket, buf, len);</span><br></pre></td></tr></table></figure><br>虽然看起来很简单,但是这个操作需要再内核空间和用户空间4次上下文切换,以及4次数据拷贝。下图展示了具体过程<br><img src="/java-zero-copy/figure1.gif" class="" title="传统的数据拷贝过程"><br>下图展示了上下文切换过程<br><img src="/java-zero-copy/figure2.gif" class="" title="上下文切换"></p>
<p>主要的步骤如下:</p>
<ol>
<li><code>read()</code>方法从user mode 转换到 kernel mode。在read内部是发一起了一次系统调用<code>sys_read()</code>从文件读取数据。第一次数据拷贝是由DMA引擎来执行,DMA从磁盘读取文件,然后将数据保存到内核缓冲区中。</li>
<li>请求的数据被从内核缓冲区拷贝到用户缓冲区,<code>read()</code>方法返回。这引起了第二次的上下文切换。现在数据是在用户空间中的缓冲区中。</li>
<li><code>send()</code>方法调用引起用户空间到内核空间的切换。这次会将数据从用户空间拷贝到内核缓冲区。这一次数据是放置到另外一个内核缓冲区中,与目的socket相关联。</li>
<li><code>send()</code>方法返回,又引起了一次上下文切换。DMA将数据从内核缓冲区拷贝到网卡缓冲区中,这是第四次数据拷贝。</li>
</ol>
<p>我们为什么不直接将数据拷贝到用户空间,而要经过内核空间呢?首先因为用户进程没有办法直接读取硬盘,这是基于保护的目的,都要经过操作系统的处理,才能读取到硬盘内容;其次这是因为操作系统引入内核缓冲区是为了提升性能。操作系统读取数据都会预读取一些数据,这样在应用程序读取额外的数据时,可以不用发起系统调用从硬盘中读取,而是直接从内核缓冲区获取即可。而写入过程,可以完全实现为异步过程。既应用程序只需要将数据写入到内核缓冲区中,而不是写入到磁盘中。<br>但是,设想当前应用程序需要处理的数据要远远大于内核空间缓冲区的大小。而此时,数据需要在磁盘,内核缓冲区,用户空间中来回拷贝。这会严重影响性能。<br>Zero copy技术是解决这个问题的方法。</p>
<h2 id="数据传输:zero-copy方法"><a href="#数据传输:zero-copy方法" class="headerlink" title="数据传输:zero copy方法"></a>数据传输:zero copy方法</h2><p>如果你仔细检查上面的过程,你会发现第二次和第三次数据拷贝可以省略。应用程序针对这些数据什么也不做。因此数据可以被直接从内核缓冲区拷贝到socket buffer中。<code>transferTo()</code>方法可以完成这个操作。下面展示了此方法<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">transferTo</span><span class="params">(<span class="type">long</span> position, <span class="type">long</span> count, WritableByteChannel target)</span>;</span><br></pre></td></tr></table></figure><br><code>transferTo()</code>方法将数据从文件channel拷贝到target channel中。这个方法依赖底层操作系统对于zero copy的支持。在UNIX或linux中,使用的是<code>sendfile()</code>系统调用。如下所示:<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string"><sys/socket.h></span></span></span><br><span class="line"><span class="type">ssize_t</span> <span class="title function_">sendfile</span><span class="params">(<span class="type">int</span> out_fd, <span class="type">int</span> in_fd, <span class="type">off_t</span> *offset, <span class="type">size_t</span> count)</span>;</span><br></pre></td></tr></table></figure><br>下图展示了<code>transferTo()</code>方法执行过程<br><img src="/java-zero-copy/figure3.gif" class="" title="transferTo过程"></p>
<p>下图展示了具体的上下文切换<br><img src="/java-zero-copy/figure4.gif" class="" title="上下文切换"></p>
<p><code>transferTo()</code>方法执行过程如下:</p>
<ol>
<li>DMA引擎将文件内容拷贝到内核缓冲区。然后数据从内核缓冲区拷贝到socket buffer中。(涉及到两次数据拷贝)</li>
<li>第三次数据拷贝发生在DMA引擎将数据从socket buffer拷贝到网卡中。</li>
</ol>
<p>我们将上下文切换从4次降低到2次,数据拷贝从4次降低到3次(其中仅有一个数据拷贝需要CPU参与,图中序号2)。但是这还没有达到zero copy的目的。如果底层网卡支持gather操作,那么我们可以减少内核空间中的数据重复。在linux kernel2.4及以后版本中,socket buffer已经支持了这个操作。这个方法不仅仅减少了上下文切换并且也消除了CPU参与的数据拷贝。具体如下:</p>
<ol>
<li><code>transferTo()</code>方法将文件内容拷贝到内核缓冲区,由DMA引擎执行</li>
<li>不需要将数据拷贝进socket buffer中,仅仅将数据的位置以及数据长度添加到socket buffer中。DMA引擎直接将kernel buffer中的数据拷贝到网卡中。<br>下图展示了包含gather操作的<code>transferTo()</code><img src="/java-zero-copy/figure5.gif" class="" title="gather操作的transferTo方法">
</li>
</ol>
<h2 id="性能比较"><a href="#性能比较" class="headerlink" title="性能比较"></a>性能比较</h2><p>使用java实现文件传输,采用传统的IO和nio来分别实现进行对比。完整代码<a href="https://github.com/lightnine/j-zerocopy">参考</a>.其中客户端是主要的视线,服务端仅仅读取数据。</p>
<h3 id="传统IO-client-代码"><a href="#传统IO-client-代码" class="headerlink" title="传统IO client 代码"></a>传统IO client 代码</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 1. create socket and connect to server</span></span><br><span class="line"> <span class="keyword">try</span> {</span><br><span class="line"> socket = <span class="keyword">new</span> <span class="title class_">Socket</span>(Common.SERVER, port);</span><br><span class="line"> System.out.println(<span class="string">"Connected with server "</span> + socket.getInetAddress() + <span class="string">":"</span> + socket.getPort());</span><br><span class="line"> } <span class="keyword">catch</span> (UnknownHostException e) {</span><br><span class="line"> System.out.println(e);</span><br><span class="line"> System.exit(Common.ERROR);</span><br><span class="line"> } <span class="keyword">catch</span> (IOException e) {</span><br><span class="line"> System.out.println(e);</span><br><span class="line"> System.exit(Common.ERROR);</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="comment">// 2. send data to server</span></span><br><span class="line"> <span class="keyword">try</span> {</span><br><span class="line"> inputStream = Files.newInputStream(Paths.get(fileName));</span><br><span class="line"> output = <span class="keyword">new</span> <span class="title class_">DataOutputStream</span>(socket.getOutputStream());</span><br><span class="line"> <span class="type">long</span> <span class="variable">start</span> <span class="operator">=</span> System.currentTimeMillis();</span><br><span class="line"> <span class="type">byte</span>[] b = <span class="keyword">new</span> <span class="title class_">byte</span>[<span class="number">4096</span>];</span><br><span class="line"> <span class="type">long</span> <span class="variable">read</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line"> <span class="type">long</span> <span class="variable">total</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line"> <span class="comment">// read function cause user mode to kernel mode,</span></span><br><span class="line"> <span class="comment">// and DMA engine read file content from disk to kernel buffer</span></span><br><span class="line"> <span class="comment">// then copy kernel buffer to the b array. This cause another context switch</span></span><br><span class="line"> <span class="comment">// then when read return, cause kernel mode to user mode</span></span><br><span class="line"> <span class="comment">// Summary: two context switch, two copy(one cpu copy)</span></span><br><span class="line"> <span class="keyword">while</span> ((read = inputStream.read(b)) >= <span class="number">0</span>) {</span><br><span class="line"> total = total + read;</span><br><span class="line"> System.out.println(<span class="string">"total size:"</span> + total);</span><br><span class="line"> <span class="comment">// write function cause user mode to kernel mode,</span></span><br><span class="line"> <span class="comment">// and copy data from b array to socket buffer,</span></span><br><span class="line"> <span class="comment">// then DMA engine copy socket buffer to nic(network interface) buffer</span></span><br><span class="line"> <span class="comment">// then when write return, cause kernel mode to user mode,</span></span><br><span class="line"> <span class="comment">// Summary: two context switch, two copy(one cpu copy)</span></span><br><span class="line"> output.write(b);</span><br><span class="line"> }</span><br><span class="line"> System.out.println(<span class="string">"bytes send: "</span> + total + <span class="string">" and totalTime(ms):"</span> + (System.currentTimeMillis() - start));</span><br><span class="line"> } <span class="keyword">catch</span> (IOException e) {</span><br><span class="line"> System.out.println(e);</span><br><span class="line"> }</span><br></pre></td></tr></table></figure>
<h3 id="nio-client-代码"><a href="#nio-client-代码" class="headerlink" title="nio client 代码"></a>nio client 代码</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testSendfile</span><span class="params">()</span> <span class="keyword">throws</span> IOException {</span><br><span class="line"> <span class="comment">// 1. get file size(bytes)</span></span><br><span class="line"> <span class="type">Path</span> <span class="variable">path</span> <span class="operator">=</span> Paths.get(fileName);</span><br><span class="line"> <span class="type">long</span> <span class="variable">fsize</span> <span class="operator">=</span> Files.size(path);</span><br><span class="line"></span><br><span class="line"> <span class="type">SocketAddress</span> <span class="variable">sad</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">InetSocketAddress</span>(Common.SERVER, port);</span><br><span class="line"> <span class="type">SocketChannel</span> <span class="variable">sc</span> <span class="operator">=</span> SocketChannel.open();</span><br><span class="line"> sc.connect(sad);</span><br><span class="line"> sc.configureBlocking(<span class="literal">true</span>);</span><br><span class="line"> <span class="type">FileInputStream</span> <span class="variable">fis</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">FileInputStream</span>(fileName);</span><br><span class="line"> <span class="type">FileChannel</span> <span class="variable">fc</span> <span class="operator">=</span> fis.getChannel();</span><br><span class="line"> <span class="type">long</span> <span class="variable">start</span> <span class="operator">=</span> System.currentTimeMillis();</span><br><span class="line"> <span class="type">long</span> <span class="variable">curnset</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line"> <span class="comment">// in linux kernel 2.4 and later</span></span><br><span class="line"> <span class="comment">// transferTo() function cause user mode to kernel mode</span></span><br><span class="line"> <span class="comment">// DMA engine copy data from disk to kernel buffer</span></span><br><span class="line"> <span class="comment">// then just copy data position and data length to kernel buffer</span></span><br><span class="line"> <span class="comment">// then DMA engine copy kernel buffer to NIC buffer</span></span><br><span class="line"> <span class="comment">// when transferTo return, cause another context switch</span></span><br><span class="line"> <span class="comment">// Summary: two context switch, two copy(zero CPU copy)</span></span><br><span class="line"> curnset = fc.transferTo(<span class="number">0</span>, fsize, sc);</span><br><span class="line"> System.out.println(<span class="string">"total bytes transferred: "</span> + curnset + <span class="string">" and time taken in MS: "</span> +</span><br><span class="line"> (System.currentTimeMillis() - start) );</span><br><span class="line"></span><br><span class="line"> fc.close();</span><br><span class="line"> fis.close();</span><br><span class="line"> }</span><br></pre></td></tr></table></figure>
<p>性能比较如下:</p>
<div class="table-container">
<table>
<thead>
<tr>
<th>file size</th>
<th>traditional(ms)</th>
<th>nio(ms)</th>
</tr>
</thead>
<tbody>
<tr>
<td>12MB</td>
<td>50</td>
<td>18</td>
</tr>
<tr>
<td>221MB</td>
<td>690</td>
<td>314</td>
</tr>
<tr>
<td>2.5G</td>
<td>15496</td>
<td>2610</td>
</tr>
</tbody>
</table>
</div>
<p>评测环境:</p>
<ol>
<li>java : openjdk version “1.8.0_382”, OpenJDK Runtime Environment (build 1.8.0_382-b05), OpenJDK 64-Bit Server VM (build 25.382-b05, mixed mode)</li>
<li>linux: CentOS Linux release 7.6 (Final)</li>
<li>kernel: 4.14.0_1-0-0-51</li>
</ol>
</div>
<footer class="post-footer">
<div class="post-tags">
<a href="/tags/java/" rel="tag"># java</a>
<a href="/tags/linux/" rel="tag"># linux</a>
<a href="/tags/zero-copy/" rel="tag"># zero-copy</a>
</div>
<div class="post-nav">
<div class="post-nav-next post-nav-item">
<a href="/Read-Write-locks-in-java-java%E4%B8%AD%E7%9A%84%E8%AF%BB%E5%86%99%E9%94%81.html" rel="next" title="Read/Write locks in java(java中的读写锁)">
<i class="fa fa-chevron-left"></i> Read/Write locks in java(java中的读写锁)
</a>
</div>
<span class="post-nav-divider"></span>
<div class="post-nav-prev post-nav-item">
<a href="/Top-5-things-every-apache-kafka-developer-should-know.html" rel="prev" title="Top 5 things every apache kafka developer should know">
Top 5 things every apache kafka developer should know <i class="fa fa-chevron-right"></i>
</a>
</div>
</div>
</footer>
</div>
</article>
<div class="post-spread">
</div>
</div>
</div>
</div>
<div class="sidebar-toggle">
<div class="sidebar-toggle-line-wrap">
<span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
<span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
<span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
</div>
</div>
<aside id="sidebar" class="sidebar">
<div class="sidebar-inner">
<ul class="sidebar-nav motion-element">
<li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
文章目录
</li>
<li class="sidebar-nav-overview" data-target="site-overview-wrap">
站点概览
</li>
</ul>
<section class="site-overview-wrap sidebar-panel">
<div class="site-overview">
<div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
<p class="site-author-name" itemprop="name"></p>
<p class="site-description motion-element" itemprop="description"></p>
</div>
<nav class="site-state motion-element">
<div class="site-state-item site-state-posts">
<a href="/archives/%7C%7C%20archive">
<span class="site-state-item-count">37</span>
<span class="site-state-item-name">日志</span>
</a>
</div>
<div class="site-state-item site-state-categories">
<a href="/categories/index.html">
<span class="site-state-item-count">22</span>
<span class="site-state-item-name">分类</span>
</a>
</div>
<div class="site-state-item site-state-tags">
<a href="/tags/index.html">
<span class="site-state-item-count">45</span>
<span class="site-state-item-name">标签</span>
</a>
</div>
</nav>
<div class="feed-link motion-element">
<a href="/atom.xml" rel="alternate">
<i class="fa fa-rss"></i>
RSS
</a>
</div>
</div>
</section>
<!--noindex-->
<section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
<div class="post-toc">
<div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#java-zero-copy"><span class="nav-number">1.</span> <span class="nav-text">java zero copy</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%95%B0%E6%8D%AE%E4%BC%A0%E8%BE%93-%E4%BC%A0%E7%BB%9F%E6%96%B9%E6%B3%95"><span class="nav-number">1.1.</span> <span class="nav-text">数据传输:传统方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%95%B0%E6%8D%AE%E4%BC%A0%E8%BE%93%EF%BC%9Azero-copy%E6%96%B9%E6%B3%95"><span class="nav-number">1.2.</span> <span class="nav-text">数据传输:zero copy方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%80%A7%E8%83%BD%E6%AF%94%E8%BE%83"><span class="nav-number">1.3.</span> <span class="nav-text">性能比较</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BC%A0%E7%BB%9FIO-client-%E4%BB%A3%E7%A0%81"><span class="nav-number">1.3.1.</span> <span class="nav-text">传统IO client 代码</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#nio-client-%E4%BB%A3%E7%A0%81"><span class="nav-number">1.3.2.</span> <span class="nav-text">nio client 代码</span></a></li></ol></li></ol></li></ol></div>
</div>
</section>
<!--/noindex-->
</div>
</aside>
</div>
</main>
<footer id="footer" class="footer">
<div class="footer-inner">
<div class="copyright">© <span itemprop="copyrightYear">2024</span>
<span class="with-love">
<i class="fa fa-user"></i>
</span>
<span class="author" itemprop="copyrightHolder">liang</span>
</div>
<div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>
<span class="post-meta-divider">|</span>
<div class="theme-info">主题 — <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>
</div>
</footer>
<div class="back-to-top">
<i class="fa fa-arrow-up"></i>
</div>
</div>
<script type="text/javascript">
if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
window.Promise = null;
}
</script>
<script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
<script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
<script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
<script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
<script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
<script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>
</body>
</html>