GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — nathanchen.github.com/14457412438314.html at master · nathanchen/nathanchen.github.com Expand file tree/ Copy path14457412438314.htmlMore file actions 667 lines (418 loc) · 25.2 KB / Copy path14457412438314.htmlFile metadata and controls667 lines (418 loc) · 25.2 KB 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 <!doctype html> <html class="no-js" lang="en"> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <title> Java NIO杂2 - NathanCHEN </title> <link href="atom.xml" rel="alternate" title="NathanCHEN" type="application/atom+xml"> <link rel="stylesheet" href="asset/css/foundation.min.css"/> <link rel="stylesheet" href="asset/css/docs.css"/> <link rel="stylesheet" href="asset/css/my.css"/> <script src="asset/js/vendor/modernizr.js"></script> <script src="asset/js/vendor/jquery.js"></script> <script src="asset/highlightjs/highlight.pack.js"></script> <link href="asset/highlightjs/styles/github.css" media="screen, projection" rel="stylesheet" type="text/css"> <script>hljs.initHighlightingOnLoad();</script> </head> <body class="antialiased hide-extras"> <div class="marketing off-canvas-wrap" data-offcanvas> <div class="inner-wrap"> <nav class="top-bar docs-bar hide-for-small" data-topbar> <section class="top-bar-section"> <div class="row"> <div style="position: relative;width:100%;"> <div style="position: absolute; width:100%;"> <ul id="main-menu" class="left"> <li id="menu_item_index"><a href="index.html">HOME</a></li> <li id="menu_item_archives"><a href="archives.html">Archives</a></li> <li id="menu_item_about"><a href="about.html">ABOUT</a></li> </ul> <ul class="right" id="search-wrap"> <li> <form target="_blank" action="http://google.com/search" method="get"> <input type="hidden" name="q" value="site:nathanchen.github.io"/> <input tabindex="1" type="search" name="q" placeholder="Search"/> </form> </li> </ul> </div> </div> </div> </section> </nav> <nav class="tab-bar show-for-small"> <a href="javascript:void(0)" class="left-off-canvas-toggle menu-icon"> <span> NathanCHEN</span> </a> </nav> <aside class="left-off-canvas-menu"> <ul class="off-canvas-list"> <li><a href="index.html">HOME</a></li> <li><a href="archives.html">Archives</a></li> <li><a href="about.html">ABOUT</a></li> <li><label>Categories</label></li> <li><a href="Java.html">Java</a></li> <li><a href="JavaScript.html">JavaScript</a></li> <li><a href="Ngnix.html">Ngnix</a></li> <li><a href="tomcat.html">tomcat</a></li> <li><a href="spring.html">spring</a></li> <li><a href="RabbitMQ.html">RabbitMQ</a></li> <li><a href="ELK.html">ELK</a></li> <li><a href="%E7%BD%91%E7%BB%9C.html">网络</a></li> <li><a href="%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB.html">源码阅读</a></li> <li><a href="others.html">others</a></li> <li><a href="%E6%95%B0%E6%8D%AE%E5%BA%93.html">数据库</a></li> <li><a href="PAXOS.html">PAXOS</a></li> <li><a href="%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90Java%20Web%E6%8A%80%E6%9C%AF%E5%86%85%E5%B9%95.html">深入分析Java Web技术内幕</a></li> <li><a href="Java7%20Concurrency%20Cookbook.html">Java7 Concurrency Cookbook</a></li> <li><a href="GoogleDevelopersWebFundamentals.html">GoogleDevelopersWebFundamentals</a></li> </ul> </aside> <a class="exit-off-canvas" href="#"></a> <section id="main-content" role="main" class="scroll-container"> <script type="text/javascript"> $(function () { $('#menu_item_index').addClass('is_active'); }); </script> <div class="row"> <div class="large-8 medium-8 columns"> <div class="markdown-body article-wrap"> <div class="article"> <h1>Java NIO杂2</h1> <div class="read-more clearfix"> <span class="date">2015/10/25</span> <span class="comments"> </span> </div> </div> <!-- article --> <div class="article-content"> <p>scatter和gather用于描述从Channel中读取或者写入到Channel的操作</p> <p>分散(scatter)从Channel中读取是指在读操作时将读取的数据写入多个buffer中。</p> <p>聚集(gather)写入Channel是指在写操作时将多个buffer的数据写入同一个Channel。</p> <p>scatter和gather经常用于需要将传输的数据分开处理的场合,例如传输一个由消息头和消息体组成的消息,你可能会将消息体和消息头分散到不同的buffer中,这样你可以方便的处理消息头和消息体。</p> <h5 id="toc_0">Scattering Reads</h5> <p><img src="img/javaio3.png" alt=""/></p> <pre><code>ByteBuffer header = ByteBuffer.allocate(128); ByteBuffer body = ByteBuffer.allocate(1024); ByteBuffer[] bufferArray = { hearder, body}; channel.read(bufferArray); </code></pre> <p><code>read()</code>方法按照buffer在数组中的顺序将从channel中读取的数据写入到buffer,当一个buffer被写满后,channel紧接着向另一个buffer中写。</p> <p>Scattering Reads在移动到下一个buffer前,必须填满当前的buffer,这也意味着它不适用于动态消息(消息大小不固定)。换句话说,如果存在消息头和消息体,消息头必须完成填充,Scattering Reads才能正常工作。</p> <h5 id="toc_1">Gathering Writes</h5> <p>Gathering Writes是指数据从多个buffer写入到同一个channel</p> <p><img src="img/javaio4.png" alt=""/></p> <pre><code>ByteBuffer header = ByteBuffer.allocate(128); ByteBuffer body = ByteBuffer.allocate(1024); //write data into buffers ByteBuffer[] bufferArray = { header, body }; channel.write(bufferArray); </code></pre> <p><code>write()</code>方法会按照buffer在数组中的顺序,将数据写入到channel,注意只有position和limit之间的数据才能被写入。</p> <p>Gathering Writes能较好的处理动态消息。</p> <blockquote> <p>在Java NIO中,如果两个通道中有一个是FileChannel,那你可以直接将数据从一个channel传输到另一个channel。</p> </blockquote> <h5 id="toc_2">transferFrom()</h5> <p>FileChannel的<code>transferFrom()</code>方法可以将数据从源通道传输到FileChannel中。</p> <pre><code>RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt", "rw"); FileChannel fromChannel = fromFile.getChannel(); RandomAccessFile toFile = new RandomAccessFile("toFile.txt", "rw"); FileChannel toChannel = toFile.getChannel(); long position = 0; long count = fromChannel.size(); toChannel.transferFrom(position, count, fromChannel); </code></pre> <blockquote> <p>Selector(选择器)是Java NIO中能够检测一到多个NIO通道,并能够知晓通道是否为诸如读写事件做好准备的组件。这样一个单独的线程可以管理多个channel,从而管理多个网络连接。</p> </blockquote> <h5 id="toc_3">为什么使用Selector</h5> <p>可以只用一个线程处理所有的通道。对于操作系统来说,线程之间上下文切换的开销很大,而且每个线程都要占用系统的一些资源。</p> <p>下面是单线程使用一个Selector处理3个channel的示例:</p> <h5 id="toc_4">Selector的创建</h5> <p>通过调用<code>Selector.open()</code>方法创建一个Selector,如下:</p> <pre><code>Selector selector = Selector.open(); </code></pre> <h5 id="toc_5">向Selector注册通道</h5> <p>为了将Channel和Selector配合使用,必须将channel注册到selector上。通过<code>SelectableChannel.register()</code>方法来实现,如下:</p> <pre><code>channel.configureBlocking(false); SelectionKey key = channel.register(selector, Selectionkey.OP_READ); </code></pre> <p>与Selector一起使用时,Channel必须处于非阻塞模式下。这意味着<strong>不能将FileChannel与Selector一起使用</strong>,因为FileChannel不能切换到非阻塞模式。而套接字通道都可以。</p> <p><code>register()</code>方法的第二个参数。这是一个<code>interest集合</code>,意思是在通过Selector监听Channel时对什么事件感兴趣。可以监听四种不同类型的事件:</p> <ul> <li>Connect</li> <li>Accept</li> <li>Read</li> <li>Write</li> </ul> <p>某个channel成功连接到另一个服务器称为<code>连接就绪</code>。<code>SelectionKey.OP_CONNECT</code></p> <p>一个server socket channel准备好接收新进入的连接称为<code>接收就绪</code>。<code>SelectionKey.OP_ACCEPT</code></p> <p>一个有数据可读的通道可以说是<code>读就绪</code>。<code>SelectionKey.OP_READ</code></p> <p>等待写数据的通道可以说是<code>写就绪</code>。<code>SelectionKey.OP_WRITE</code></p> <p>如果你对不止一种事件感兴趣,那么可以用“位或”操作符将常量连接起来,如下:</p> <pre><code>int interestSet = SelectionKey.OP_READ | SelectionKey.OP_WRITE; </code></pre> <h4 id="toc_6">SelectionKey</h4> <p>当向Selector注册Channel时,register()方法会返回一个SelectionKey对象。这个对象包含了一些你感兴趣的属性:</p> <ul> <li>interest集合</li> <li>ready集合</li> <li>Channel</li> <li>Selector</li> <li>附加的对象(可选)</li> </ul> <h5 id="toc_7">interest集合</h5> <p>interest集合是你所选择的感兴趣的事件集合。</p> <p>可以通过SelectionKey读写interest集合:</p> <pre><code>int interestSet = selectionKey.interestOps(); boolean isInterestedInAccept = (interestSet & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT; boolean isInterestedInConnect = interestSet & SelectionKey.OP_CONNECT; boolean isInterestedInRead = interestSet & SelectionKey.OP_READ; boolean isInterestedInWrite = interestSet & SelectionKey.OP_WRITE; </code></pre> <p>用'位与'操作interest集合和给定的selectionKey常量,可以确定某个确定的事件是否在interest集合中。</p> <h5 id="toc_8">ready集合</h5> <p>ready集合是通道已经准备就绪的操作的集合。在一次选择(selection)之后,你会首先访问这个ready set。</p> <pre><code>int readySet = selectionKey.readyOps(); </code></pre> <h5 id="toc_9">Channel + Selector</h5> <p>从SelectionKey访问Channel和Selector:</p> <pre><code>Channel channel = selectionKey.channel(); Selector selector = selectionKey.selector(); </code></pre> <h5 id="toc_10">附加的对象</h5> <p>可以将一个对象或者更多信息附着到SelectionKey上,这样就能方便的识别某个给定的通道。</p> <p>例如,可以附加与通道一起使用的Buffer,或者包含聚集数据的某个对象,使用方法:</p> <pre><code>selectionKey.attach(theObject); Object attachedObj = selectionKey.attachment(); </code></pre> <p>还可以在用register()方法向Selector注册Channel的时候附加对象。</p> <pre><code>SelectionKey key = channel.register(selector, SelectionKey.OP_READ, theObject); </code></pre> <h5 id="toc_11">通过Selector选择通道</h5> <p>一旦向Selector注册了一个或多个通道,就可以调用几个重载的<code>select()</code>方法。这些方法返回你所感兴趣的事件、已经准备就绪的那些通道。</p> <p>也就是,如果你对'读就绪'的通道感兴趣,<code>select()</code>方法会返回读事件已经就绪的那些通道。</p> <ul> <li><p><code>select()</code>阻塞到至少有一个通道在你注册的事件上就绪了。</p></li> <li><p><code>select(long timeout)</code>和<code>select()</code>一样,除了最长会阻塞timeout毫秒(参数)。</p></li> <li><p><code>selectNow()</code>不会阻塞,不管什么通道就绪都立刻返回(译者注:此方法执行非阻塞的选择操作。如果自从前一次选择操作后,没有通道变成可选择的,则此方法直接返回零。)。</p></li> </ul> <p><code>select()</code>方法返回的int值表示有多少通道已经就绪。自上次调用<code>select()</code>方法后有多少通道变成就绪状态。</p> <pre><code>如果调用`select()`方法,因为有一个通道变成就绪状态,返回了1 若再次调用`select()`方法,如果另一个通道就绪了,它会再次返回1。 如果对第一个就绪的channel没有做任何操作,现在就有两个就绪的通道, 但在每次`select()`方法调用之间,只有一个通道就绪了。 </code></pre> <h5 id="toc_12"><code>selectedKeys()</code></h5> <p>一旦调用了<code>select()</code>方法,并且返回值表明有一个或者多个通道就绪了,然后可以通过调用selector的<code>selectedKeys()</code>方法,访问'已选择键集(selected key set)'中的就绪通道。如下所示:</p> <pre><code>Set selectedKeys = selector.selectedKeys(); </code></pre> <p>当像Selector注册Channel时,<code>Channel.register()</code>方法会返回一个SelectionKey 对象。这个对象代表了注册到该Selector的通道。可以通过SelectionKey的<code>selectedKeySet()</code>方法访问这些对象。</p> <pre><code>Set selectedKeys = selector.selectedKeys(); Iterator keyIterator = selectedKeys.iterator(); while(keyIterator.hasNext()) { SelectionKey key = keyIterator.next(); if(key.isAcceptable()) { // a connection was accepted by a ServerSocketChannel. } else if (key.isConnectable()) { // a connection was established with a remote server. } else if (key.isReadable()) { // a channel is ready for reading } else if (key.isWritable()) { // a channel is ready for writing } keyIterator.remove(); } </code></pre> <p>这个循环遍历已选择键集中的每个键,并检测各个键所对应的通道的就绪事件。</p> <p>注意每次迭代末尾的<code>keyIterator.remove()</code>调用。Selector不会自己从已选择键集中移除SelectionKey实例。必须在处理完通道时自己移除。</p> <p><code>SelectionKey.channel()</code>方法返回的通道需要转型成你要处理的类型,如ServerSocketChannel或SocketChannel等。</p> <h5 id="toc_13">wakeUp()</h5> <p>某个线程调用<code>select()</code>方法后阻塞了,即使没有通道已经就绪,也有办法让其从<code>select()</code>方法返回。只要让其它线程在第一个线程调用<code>select()</code>方法的那个对象上调用<code>Selector.wakeup()</code>方法即可。阻塞在<code>select()</code>方法上的线程会立马返回。</p> <p>如果有其它线程调用了<code>wakeup()</code>方法,但当前没有线程阻塞在<code>select()</code>方法上,下个调用<code>select()</code>方法的线程会立即'醒来(wake up)'</p> <h5 id="toc_14">close()</h5> <p>用完Selector后调用其<code>close()</code>方法会关闭该Selector,且使注册到该Selector上的所有SelectionKey实例无效。通道本身并不会关闭。</p> <h5 id="toc_15">完整的示例</h5> <p>这里是一个完整的示例,打开一个Selector,注册一个通道注册到这个Selector上,然后持续监控这个Selector的四种事件(接受,连接,读,写)是否就绪</p> <pre><code>Selector selector = Selector.open(); channel.configureBlocking(false); SelectionKey key = channel.register(selector, SelectionKey.OP_READ); while(true) { int readyChannels = selector.select(); if(readyChannels == 0) continue; Set selectedKeys = selector.selectedKeys(); Iterator keyIterator = selectedKeys.iterator(); while(keyIterator.hasNext()) { SelectionKey key = keyIterator.next(); if(key.isAcceptable()) { // a connection was accepted by a ServerSocketChannel. } else if (key.isConnectable()) { // a connection was established with a remote server. } else if (key.isReadable()) { // a channel is ready for reading } else if (key.isWritable()) { // a channel is ready for writing } keyIterator.remove(); } } </code></pre> <h4 id="toc_16">Reference</h4> <p><a href="http://ifeve.com/java-nio-scattergather/">http://ifeve.com/java-nio-scattergather/</a></p> <p><a href="http://ifeve.com/java-nio-channel-to-channel/">http://ifeve.com/java-nio-channel-to-channel/</a></p> <p><a href="http://ifeve.com/selectors/">http://ifeve.com/selectors/</a></p> </div> <div class="row"> <div class="large-6 columns"> <p class="text-left" style="padding:15px 0px;"> <a href="14457412438464.html" title="Previous Post: Java NIO杂3">« Java NIO杂3</a> </p> </div> <div class="large-6 columns"> <p class="text-right" style="padding:15px 0px;"> <a href="14457412438170.html" title="Next Post: Java NIO杂1">Java NIO杂1 »</a> </p> </div> </div> <div class="comments-wrap"> <div class="share-comments"> <div id="disqus_thread"></div> <script> /** * RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS. * LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables */ /* var disqus_config = function () { this.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable }; */ (function() { // DON'T EDIT BELOW THIS LINE var d = document, s = d.createElement('script'); s.src = '//nathanchen123.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })(); </script> <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript" rel="nofollow">comments powered by Disqus.</a></noscript> </div> </div> </div> <!-- article-wrap --> </div> <!-- large 8 --> <div class="large-4 medium-4 columns"> <div class="hide-for-small"> <div id="sidebar" class="sidebar"> <div id="site-info" class="site-info"> <h1>NathanCHEN</h1> <div class="site-des"></div> <div class="social"> <a class="rss" href="atom.xml" title="RSS">RSS</a> </div> </div> <div id="site-categories" class="side-item "> <div class="side-header"> <h2>Contact</h2> </div> <div class="side-content"> <ul class="posts-list"> <li class="post"> <p class="email-addr">tringchen AT gmail.com</p> <p class="email-addr">江苏 · 南京</p> </li> </ul> </div> </div> <div id="site-categories" class="side-item "> <div class="side-header"> <h2>Categories</h2> </div> <div class="side-content"> <p class="cat-list"> <a href="Java.html"><strong>Java</strong></a> <a href="JavaScript.html"><strong>JavaScript</strong></a> <a href="Ngnix.html"><strong>Ngnix</strong></a> <a href="tomcat.html"><strong>tomcat</strong></a> <a href="spring.html"><strong>spring</strong></a> <a href="RabbitMQ.html"><strong>RabbitMQ</strong></a> <a href="ELK.html"><strong>ELK</strong></a> <a href="%E7%BD%91%E7%BB%9C.html"><strong>网络</strong></a> <a href="%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB.html"><strong>源码阅读</strong></a> <a href="others.html"><strong>others</strong></a> <a href="%E6%95%B0%E6%8D%AE%E5%BA%93.html"><strong>数据库</strong></a> <a href="PAXOS.html"><strong>PAXOS</strong></a> <a href="%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90Java%20Web%E6%8A%80%E6%9C%AF%E5%86%85%E5%B9%95.html"><strong>深入分析Java Web技术内幕</strong></a> <a href="Java7%20Concurrency%20Cookbook.html"><strong>Java7 Concurrency Cookbook</strong></a> <a href="GoogleDevelopersWebFundamentals.html"><strong>GoogleDevelopersWebFundamentals</strong></a> </p> </div> </div> <div id="site-categories" class="side-item"> <div class="side-header"> <h2>Recent Posts</h2> </div> <div class="side-content"> <ul class="posts-list"> <li class="post"> <a href="14608176804744.html">HTTP/2</a> </li> <li class="post"> <a href="14606892007159.html">Web页面缓存</a> </li> <li class="post"> <a href="14606396114001.html">Java中的Object对象</a> </li> <li class="post"> <a href="14606028630903.html">深入Class文件结构</a> </li> <li class="post"> <a href="14605288849994.html">Thread Synchronization Utilities</a> </li> </ul> </div> </div> </div> <!-- sidebar --> </div> <!-- hide for small --> </div><!-- large 4 --> </div><!-- row --> <div class="page-bottom clearfix"> <div class="row"> <p class="copyright">Copyright © 2016 Powered by <a target="_blank" href="http://www.mweb.im">MWeb</a>, Theme used <a target="_blank" href="http://github.com">GitHub CSS</a>.</p> </div> </div> </section> </div> </div> <script src="asset/js/foundation.min.js"></script> <script> $(document).foundation(); function fixSidebarHeight() { var w1 = $('.markdown-body').height(); var w2 = $('#sidebar').height(); if (w1 > w2) { $('#sidebar').height(w1); } ; } $(function () { fixSidebarHeight(); }) $(window).load(function () { fixSidebarHeight(); }); </script> </body> </html> |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |