<?xml version="1.0" encoding="utf-8"?>
<search>
  <entry>
    <title>村上春树《1Q84》读后感</title>
    <url>/2019/12/18/1Q84%E8%AF%BB%E5%90%8E%E6%84%9F/</url>
    <content><![CDATA[<p>看完了村上春树的《1Q84》，这应该是第五本看的他的书了，继 跑步，挪威的森林，刺杀骑士团长，海边的卡夫卡之后，不是其中最长的，好像是海边的卡夫卡还是刺杀骑士团长比较长一点，都是在微信读书上看的，比较方便，最开始在上面看的是高晓松的《鱼羊野史》，不知道为啥取这个名字，但是还是满吸引我的，不过由于去年的种种，没有很多心思把它看完，而且本身的组织形式就是比较松散的，看到哪算哪，其实一些野史部分是我比较喜欢，有些谈到人物的就不太有兴趣，而且类似于大祥哥吃的东西，反正都是哇，怎么这么好吃，嗯，太爱（niu）你（bi）了，高晓松就是这个人是我最喜欢的 xxx 家，我也没去细究过他有没有说重复过，反正是不太爱，后来因为这书还一度对战争史有了浓厚的兴趣，然而事实告诉我，大部头的战争史，其实正史我是真的啃不下去，我可能只对其中 10%的内容感兴趣，不过终于也在今年把它看完了，好像高晓松的晓说也最终季了，貌似其中讲朝鲜战争的还被和谐了，看样子是说出了一些故事（truth）。</p>
<p>本来只是想把 《1Q84》的读后感写下，现在觉得还是把这篇当成我今年的读书总结吧，不过先从《1Q84》说起。</p>
<p>严格来讲，这不是很书面化的读后感，可能我想写的也只是像聊天一样的说下我读过的书，包括的技术博客其实也是类似的，以后或许会转变，但是目前水平如此吧，写多了可能会变好，也可能不会。</p>
<p>开始正文吧，这书有点类似于海边的卡夫卡，一开始是通过两条故事线，穿插着叙述，一条是青豆的，不算是个职业杀手的女杀手，要去解决一个经常家暴的斯文败类，穿着描述得比较性感吧，杀人方式是通过比较长的细针，从脖子后面一个精巧的位置插入，可以造成是未知原因死亡的假象，可能会推断成心梗之类的，这里有个前置的细节，就是青豆是乘坐一辆很高级的出租车，内饰什么的都非常有质感，有点不像一辆出租车，然后车里放了一首比较小众的歌，雅纳切克的《小交响曲》，但是青豆知道它，这跟后面的情节也有些许关系，这是女主人公青豆的出场；相应的男主的出场印象不是太深刻，男主叫天吾，是个不知名的作家，跟一个叫小松的编辑有比较好的关系，虽然天吾还没有拿到比较有分量的奖项，但是小松很看好他，也让他帮忙审校一个新作家奖的投稿文章，虽然天吾自身还没获得过这个奖，天吾还有个正式工作，是当数学老师，天吾在学生时代是个数学天才，但后面有对文学产生了兴趣，文学还不足以养活自己，靠着教课还是能保持温饱；</p>
<p>接下来是正式故事的起点了，就是小松收到了一部小说投稿，名叫《空气蛹》，是个叫深绘里的女孩子投的稿，小松对他赋予了很高的评价，这里好像记岔了，好像是天吾对这部小说很有好感，但是小松比较怀疑，然后小松看了之后也有了浓厚的兴趣，这里就是开端了，小松想让天吾来重写润色这部《空气蛹》，因为故事本身很有分量，但是描写手法叙事方式等都很拙劣，而天吾正好擅长这个，小松对天吾的评价是，描写技巧无可挑剔，就是故事主体的火花还没际遇迸发，需要一个导火索，这个就可以类比我们程序员，很多比较初中级的程序员主要擅长在原来的代码上修修改改或者给他分配个小功能，比较高级的程序员就需要能做一些项目的架构设计，核心的技术方案设计，以前我也觉得写文档这个比较无聊，但是当一个项目真的比较庞大，复杂的时候，整体和核心部分的架构设计和方案还是需要有文档沉淀的，不然别人不知道没法接受，自己过段时间也会忘记。</p>
<p>对于小松的这个建议，他的初衷是想搅一搅这个死气沉沉套路颇深的文坛，因为本身《空气蛹》这部小说的内容很吸引人，小松想通过天吾的润色补充让这部小说冲击新人奖，有种恶作剧的意图，天吾对此表示很多担心和顾虑，小松的这个建议其实也是一种文学作假，有两方面的担心，一方面是原作者深绘里是否同意如此操作，一方面是外界如果发现了这个事实会有什么样的后果，但是小松表示不用担心，前一步由小松牵线，让天吾跟原作者深绘里当面沟通这个代写是否被允许，结果当然是被允许了，这里有了对深绘里的初步描写，按我的理解是比较仙的感觉，然后语言沟通有些吃力，或者说有她自己的特色，当面沟通时貌似是让深绘里回去再考虑下，然后后面再由天吾去深绘里寄宿的戎野老师家沟通具体的细节。</p>
<p>2019年12月18日23:37:19 更新<br>去到戎野老师家之后，天吾知道了关于深绘里的一些事情，深绘里的父亲与戎野老师应该是老友，深绘里的父亲在当初成立了一个叫”先驱”的公社，一个独立运行的社会组织，以运营农场作为物资来源，追求更为松散的共同体，即不过分激进地公有制，进行松散的共同生活，承认私有财产，简而言之就是这样一个能稳定存活下来的独立社会组织，但是随着稳定运行，内部的激进派和稳健派开始出现分歧，不可磨合，后来两派就分裂了，深绘里的父亲，深田保留在了稳健派，但是此时其实深田保内心是矛盾的，以为一开始其实是他倡导的独立革命才组织起了这群人，然而现在他又认清了现实社会已经不太相信能通过革命来独立的可能性，后来激进派便开始越加封闭，而且进行军事训练和思想教育，而后这个先驱的激进派别便有了新的名字”黎明”，深绘里也是在此时从先驱逃离来投靠戎野老师<br>暂时先写到这，未完待续~</p>
]]></content>
      <categories>
        <category>生活</category>
        <category>读后感</category>
        <category>村上春树</category>
      </categories>
      <tags>
        <tag>读后感</tag>
      </tags>
  </entry>
  <entry>
    <title>2019年终总结</title>
    <url>/2020/02/01/2019%E5%B9%B4%E7%BB%88%E6%80%BB%E7%BB%93/</url>
    <content><![CDATA[<p>今天是农历初八了，年前一个月的时候就准备做下今年的年终总结，可是写了一点觉得太情绪化了，希望后面写个平淡点的，正好最近技术方面还没有看到一个完整成文的内容，就来写一下这一年的总结，尽量少写一点太情绪化的东西。</p>
<h3 id="跳槽"><a href="#跳槽" class="headerlink" title="跳槽"></a>跳槽</h3><p>年初换了个公司，也算换了个环境，跟前公司不太一样，做的事情方向也不同，可能是侧重点不同，一开始有些不适应，主要是压力上，会觉得压力比较大，但是总体来说与人相处的部分还是不错的，做的技术方向还是Java，这里也感谢前东家让我有机会转了Java，个人感觉杭州整个市场还是Java比较有优势，不过在开始的时候总觉得对Java有点不适应，应该值得深究的东西还是很多的，而且对于面试来说，也是有很多可以问的，后面慢慢发现除开某里等一线超一线互联网公司之外，大部分的面试还是有大概的套路跟大纲的，不过更细致的则因人而异了，面试有时候也还看缘分，面试官关注的点跟应试者比较契合的话就很容易通过面试，不然的话总会有能刁难或者理性化地说比较难回答的问题。这个后面可以单独说一下，先按下不表。<br>刚进公司没多久就负责比较重要的项目，工期也比较紧张，整体来说那段时间的压力的确是比较大的，不过总算最后结果不坏，这里应该说对一些原来在前东家都是掌握的不太好的部分，比如maven，其实maven对于java程序员来说还是很重要的，但是我碰到过的面试基本没问过这个，我自己也在后面的面试中没问过相关的，不知道咋问，比如dependence分析、冲突解决，比如对bean的理解，这个算是我一直以来的疑问点，因为以前刚开始学Java学spring，上来就是bean，但是bean到底是啥，IOC是啥，可能网上的文章跟大多数书籍跟我的理解思路不太match，导致一直不能很好的理解这玩意，到后面才理解，要理解这个bean，需要有两个基本概念，一个是面向对象，一个是对象容器跟依赖反转，还是只说到这，后面可以有专题说一下，总之自认为技术上有了不小的长进了，方向上应该是偏实用的。这个重要的项目完成后慢慢能喘口气了，后面也有一些比较紧急且工作量大的，不过在我TL的帮助下还是能尽量协调好资源。</p>
<h3 id="面试"><a href="#面试" class="headerlink" title="面试"></a>面试</h3><p>后面因为项目比较多，缺少开发，所以也参与帮忙做一些面试，这里总体感觉是面的候选人还是比较多样的，有些工作了蛮多年但是一些基础问题回答的不好，有些还是在校学生，但是面试技巧不错，针对常见的面试题都有不错的准备，不过还是觉得光靠这些面试题不能完全说明问题，真正工作了需要的是解决问题的人，而不是会背题的，退一步来说能好好准备面试还是比较重要的，也是双向选择中的基本尊重，印象比较深刻的是参加了去杭州某高校的校招面试，感觉参加校招的同学还是很多的，大部分是20年将毕业的研究生，挺多都是基础很扎实，对比起我刚要毕业时还是很汗颜，挺多来面试的同学都非常不错，那天强度也很大，从下午到那开始一直面到六七点，在这祝福那些来面试的同学，也都不容易的，能找到心仪的工作。</p>
<h3 id="技术方向"><a href="#技术方向" class="headerlink" title="技术方向"></a>技术方向</h3><p>这一年前大半部分还是比较焦虑不能恢复那种主动找时间学习的状态，可能换了公司是主要的原因，初期有个适应的过程也比较正常，总体来说可能是到九十月份开始慢慢有所改善，对这些方面有学习了下，</p>
<ul>
<li>spring方向，spring真的是个庞然大物，但是还是要先抓住根本，慢慢发散去了解其他的细节，抓住bean的生命周期，当然也不是死记硬背，让我一个个背下来我也不行，但是知道它究竟是干嘛的，有啥用，并且在工作中能用起来是最重要的</li>
<li>mysql数据库，这部分主要是关注了mvcc，知道了个大概，源码实现细节还没具体研究，有时间可以来个专题（一大堆待写的内容）</li>
<li>java的一些源码，比如aqs这种，结合文章看了下源码，一开始总感觉静不下心来看，然后有一次被LD刺激了下就看完了，包括conditionObject等</li>
<li>redis的源码，这里包括了Redis分布式锁和redis的数据结构源码，已经写成文章，不过比较着急成文，所以质量不是特别好，希望后面再来补补</li>
<li>jvm源码，这部分正好是想了解下g1收集器，大概把周志明的书看完了，但是还没完整的理解掌握，还有就是g1收集器的部分，一是概念部分大概理解了，后面是就是想从源码层面去学习理解，这也是新一年的主要计划</li>
<li>mq的部分是了解了zero copy，sendfile等，跟消息队列主题关系不大🤦‍♂️<br>这么看还是学了点东西的，希望新一年再接再厉。</li>
</ul>
<h3 id="生活"><a href="#生活" class="headerlink" title="生活"></a>生活</h3><p>住的地方没变化，主要是周边设施比较方便，暂时没找到更好的就没打算换，主要的问题是没电梯，一开始没觉得有啥，真正住起来还是觉得比较累的，希望后面租的可以有电梯，或者楼层低一点，还有就是要通下水道，第一次让师傅上门，花了两百大洋，后来自学成才了，让师傅通了一次才撑了一个月就不行了，后面自己通的差不多可以撑半年，还是比较有成就感的😀，然后就是跑步了，年初的时候去了紫金港跑步，后面因为工作的原因没去了，但是公司的跑步机倒是让我重拾起这个唯一的运动健身项目，后面因为肠胃问题，体重也需要控制，所以就周末回来也在家这边坚持跑步，下半年的话基本保持每周一次以上，比较那些跑马拉松的大牛还是差距很大，不过也是突破自我了，有一次跑了12公里，最远的距离，而且后面感觉跑十公里也不是特别吃不消了，这一年达成了300公里的目标，体重也稍有下降，比较满意的结果。</p>
<h3 id="期待"><a href="#期待" class="headerlink" title="期待"></a>期待</h3><p>希望工作方面技术方面能有所长进，生活上能多点时间陪家人，继续跑步减肥，家人健健康康的，嗯</p>
]]></content>
      <categories>
        <category>生活</category>
        <category>年终总结</category>
        <category>2019</category>
      </categories>
      <tags>
        <tag>生活</tag>
        <tag>年终总结</tag>
        <tag>2019</tag>
      </tags>
  </entry>
  <entry>
    <title>2020 年终总结</title>
    <url>/2021/03/31/2020-%E5%B9%B4%E7%BB%88%E6%80%BB%E7%BB%93/</url>
    <content><![CDATA[<h2 id="拖更原因"><a href="#拖更原因" class="headerlink" title="拖更原因"></a>拖更原因</h2><p>这篇年终总结本来应该在农历过完年就出来的，结果是对没有受疫情影响的春节放假时间空闲情况预估太良好，虽然公司调了几天假，但是因为春节期间疫情状况比较好，本来酒店都不让接待聚餐什么的，后来统统放开，结果就是从初一到初六每天要不就是去亲戚家，要不就是去酒店饭店吃饭，计划很丰满，现实很骨感，时间感觉一下就没了，然后年后感觉有点犯懒了，所以才拖到现在。</p>
<h2 id="生活-健身跑步"><a href="#生活-健身跑步" class="headerlink" title="生活-健身跑步"></a>生活-健身跑步</h2><p>去年（19 年）的时候跑步突破了 300 公里，然后20 年给自己定了个 400 公里的目标，结果意料之中的没成功，原因可能疫情算一点吧，后面买了跑步机之后，基本周末回家都能跑一下，但是最后还是只跑了300 多公里，总的keep 记录跑量也没超过 1000 公里，所以跑步这个目标还是没成功的，不过还算是比去年多跑一点，这样也算后面好突破点，后面的目标就不定的太高了，每年能比前一年多一点就好，其实跑步已经从一种减肥方式变成一种习惯了，一周一次的跑步已经比较难有效减重了，但是对于保持精力和身体状态还是很有效和重要的，只是对于目前的体重还是要多减下去一些跑步才好，太重了对膝盖负担太大了，可惜还是时间呐，游泳骑车什么的都需要更苛刻的条件和时间，饮食呢控制起来比较难（贪吃<br>终于在 3 月底之前跑到了 1000 公里，迟了三个月，不过也总算达到了，只是体重控制还是不行，有试着走走楼梯，但是感觉对膝盖负担比较大，得再想想用什么方式</p>
<p><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/WechatIMG546-1.png"></p>
<h2 id="技术成长"><a href="#技术成长" class="headerlink" title="技术成长"></a>技术成长</h2><p>一直提不起笔来写这篇年终总结还有个比较大的原因是觉得20 年的成长不如预期，大小目标都没怎么完成，比如深入了解 jvm，是想能有些深入的见解，而不再是某些点的比较片面的理解，系统性的归纳总结也比较少，每个方向或多或少有些看法和理解，但是不全面，一些东西看过了也会忘记，需要温故而知新，比如 AQS 的内容，第一次读其实理解比较浅，后面就强迫自己去读，去写，才有了一些比之前更深入的理解，因为很多文章都是带有作者思路的引导，适不适合自己都要看是否能从他的思路把它看懂，有些就差别很大，这个跟看书也一样，有些书大众一致推荐，一般情况下大多是经典的好的，但是也有可能是不太适合自己的，可能有时候机缘巧合看到的反而让人茅塞顿开，在 todo 里已经积攒了好多的点和面需要去学习实践，一方面是自己懒，一方面是时间也相对偏少，看看 21 年能不能有所提升，加强“时间管理”，哈哈</p>
<p>技术上主要是看了 mysql 的 mvcc 相关内容，rocketmq 的，redis 的代码，还有 mybatis 等，其实每一个都能写很多，也有很多值得学习的，需要全面系统学习，之前想好好画一个思维导图，将整个技术体系都梳理下，还只做了一点点，方式也有点问题，应该从大到小，而不是深度优先，细节有很多，每一个方面都有自己比较熟悉擅长的，也有不太了解的，可以做一个评分，这个也是亟待改善的，希望今年能完成。</p>
<h2 id="博客"><a href="#博客" class="headerlink" title="博客"></a>博客</h2><p>博客方面 20 年一年整是写了 53 篇，差不多是一周一篇的节奏，这个还是不错的，虽然博客质量参差不齐，但是这个更新频率还是比较好的，并且也定了个潜规则，可以一周技术一周生活，这样能缓解水文的频率，提高些技术文章的质量，虽然结果并没有好多少，不过感觉还是可以这么坚持的，能提高一些技术文章的质量那就更好了</p>
]]></content>
      <categories>
        <category>生活</category>
        <category>年终总结</category>
        <category>2020</category>
        <category>年终总结</category>
        <category>2020</category>
      </categories>
      <tags>
        <tag>生活</tag>
        <tag>年终总结</tag>
        <tag>2020</tag>
        <tag>2021</tag>
        <tag>拖更</tag>
      </tags>
  </entry>
  <entry>
    <title>2020年中总结</title>
    <url>/2020/07/11/2020%E5%B9%B4%E4%B8%AD%E6%80%BB%E7%BB%93/</url>
    <content><![CDATA[<p>很快2020 年就过了一半了，而且是今年这么特殊的一年，很多事情都发生的出乎意料，疫情这个绕不过去的话题，之前写了点比较愤青的文字，感觉不太适合发出来就烂在草稿箱里吧，这个目前一大影响估计是今年都没办法完全摘下口罩了，前面几个月来回杭州都开车，因为彭埠大桥不通行了，实在是非常不方便，每条路都灰常堵，心累，吐槽下杭州的交通规划和交警同志，工作实在做的不咋地。</p>
<p>另外一件是就是蜗壳，从前不知道黝黑蜗壳是啥意思，只是经常会在他的视频里看到，大学的时候在缘网下了一个集锦，炒鸡帅气，各种空接扣篮，越来越能明白那句“你永远不知道意外和明天不知道哪个会先来,且行且珍惜”的含义，只是听了很多道理，依然活不好这一生，知易行难，王阳明真的是这方面的大师，有空可以看看这方面的书，一直想写写我跟篮球跟蜗壳的这十几年，争取能早日写好吧，不过得找个静得下来的时候写。</p>
<p>正事方面上半年还是挺让人失望的，没有达成一些目标，应该还是能力不足吧，技术方面分析一下还是停留在看的表面层，有些实操的，或者结合业务场景的能力不太行，算是在坚持写写 blog，主要是被这个每周一篇的目标推着走，有时会比较焦虑，内容产出也还比较差，希望能在后面有些改善，可能会降低频率，只是觉得降低了也不一定能有比较好的提升，无法战胜自己的惰性，所以暂时还是坚持下这个目标吧，还有就是 coding 能力，有时候也应该刷刷题，提升思维敏捷度，大脑用太少可能生锈了，况且本来就不是很有优势，虽然失望也只能继续努力吧，日拱一卒，来日方长，加油吧~😔</p>
<p>还有就是跑步减肥了，截止今天，上半年跑了 136 公里了，因为疫情影响，农历年后是从 4 月 17 号开始跑的，去年跑到了 300 公里，奖励自己了一个手表（真的挺后悔的，还不如 200 块买个手表），今年希望可以能在这个基础上再进一步，一直跟领导说，跑步算是我坚持下来的唯一一个好习惯了，618 买了个跑步机，周末回家了可以不受天气影响的多跑跑，不过如果天气好可能还是会出去跑跑，跑步机跑道多少还是有点拘束，只是感觉可能是我还是吃得太多了🤦‍♂️，效果不是很明显，还在 80 这个坎徘徊，等于浪费了大半年，可能是年初的项目太费心力，压力比较大，吃得更多，是不是可以算工伤😄，这方面也需要好好调整，可以放得开一点，虽然不太可能一下子到位，但是总要去努力下，随着年龄成长总要承担更多，也要看得开一点，没法事事如愿，尽力就好了，减肥这个事情还在结合一些俯卧撑啥的，希望也能坚持下去，加油吧，不知道原话怎么说的，意思是人类最大的勇敢就是看透了人世间的苦难，仍然热爱生活。我当然没可能让内心变得这么强大，试着去努力吧，奥力给！</p>
]]></content>
      <categories>
        <category>生活</category>
        <category>年中总结</category>
        <category>2020</category>
      </categories>
      <tags>
        <tag>生活</tag>
        <tag>2020</tag>
        <tag>年中总结</tag>
      </tags>
  </entry>
  <entry>
    <title>2021 年中总结</title>
    <url>/2021/07/18/2021-%E5%B9%B4%E4%B8%AD%E6%80%BB%E7%BB%93/</url>
    <content><![CDATA[<p>又到半年总结时，第一次写总结类型的文章感觉挺好写的，但是后面总觉得这过去的一段时间所做的事情，能力上的成长低于预期，但是是需要总结下，找找问题，顺便展望下未来。</p>
<p>这一年做的最让自己满意的应该就是看了一些书，由折腾群洋总发起的读书打卡活动，到目前为止已经读完了这几本书，《cUrl 必知必会》，《古董局中局 1》，《古董局中局 2》，《算法图解》，《每天 5 分钟玩转 Kubernetes》《幸福了吗？》《高可用可伸缩微服务架构：基于 Dubbo、Spring Cloud和 Service Mesh》《Rust 权威指南》后面可以写个专题说说看的这些书，虽然每天打卡如果时间安排不好，并且看的书像 rust 这样比较难的话还是会有点小焦虑，不过也是个调整过程，一方面可以在白天就抽空看一会，然后也不必要每次都看很大一章，注重吸收。</p>
<p>技术上的成长的话，有一些比较小的长进吧，对于一些之前忽视的 synchronized，ThreadLocal 和 AQS 等知识点做了下查漏补缺了，然后多了解了一些 Java 垃圾回收的内容，但是在实操上还是比较欠缺，成型的技术方案，架构上所谓的优化也比较少，一些想法也还有考虑不周全的地方，还需要多花时间和心思去学习加强，特别是在目前已经有的基础上如何做系统深层次的优化，既不要是鸡毛蒜皮的，也不能出现一些不可接受的问题和故障，这是个很重要的课题，需要好好学习，后面考虑定一些周期性目标，两个月左右能有一些成果和总结。</p>
<p>另外一部分是自己的服务，因为 ucloud 的机器太贵就没续费了，所以都迁移到腾讯云的小机器上了，顺便折腾了一点点 traefik，但是还很不熟练，不太习惯这一套，一方面是 docker 还不习惯，这也加重了对这套环境的不适应，还是习惯裸机部署，另一方面就是 k8s 了，家里的机器还没虚拟化，没有很好的条件可以做实验，这也是读书打卡的一个没做好的点，整体的学习效果受限于深度和实操，后面是看都是用 traefik，也找到了一篇文章可以 traefik 转发到裸机应用，因为主仓库用的是裸机的 gogs。</p>
<p>还有就是运动减肥上，唉，这又是很大的一个痛点，基本没效果，只是还算稳定，昨天看到一个视频说还需要力量训练来增肌，以此可以提升基础代谢，打算往这个方向尝试下，因为今天没有疫情限制了，在 6 月底完成了 200 公里的跑步小目标，只是有些膝盖跟大腿根外侧不适，抽空得去看下医生，后面打算每天也能做点卷腹跟俯卧撑。</p>
<p>下半年还希望能继续多看看书，比很多网上各种乱七八糟的文章会好很多，结合豆瓣评分，找一些评价高一些的文章，但也不是说分稍低点的就不行，有些也看人是不是适合，一般 6 分以上评价比较多的就可以试试。</p>
]]></content>
      <categories>
        <category>生活</category>
        <category>年中总结</category>
        <category>2021</category>
      </categories>
      <tags>
        <tag>生活</tag>
        <tag>2021</tag>
        <tag>年中总结</tag>
        <tag>技术</tag>
        <tag>读书</tag>
      </tags>
  </entry>
  <entry>
    <title>34_Search_for_a_Range</title>
    <url>/2016/08/14/34-Search-for-a-Range/</url>
    <content><![CDATA[<h2 id="question"><a href="#question" class="headerlink" title="question"></a>question</h2><h3 id="34-Search-for-a-Range"><a href="#34-Search-for-a-Range" class="headerlink" title="34. Search for a Range"></a>34. Search for a Range</h3><p><a href="https://leetcode.com/problems/search-for-a-range/">Original Page</a></p>
<p>Given a sorted array of integers, find the starting and ending position of a given target value.</p>
<p>Your algorithm’s runtime complexity must be in the order of <em>O</em>(log <em>n</em>).</p>
<p>If the target is not found in the array, return <code>[-1, -1]</code>.</p>
<p>For example,<br>Given <code>[5, 7, 7, 8, 8, 10]</code> and target value 8,<br>return <code>[3, 4]</code>.</p>
<h2 id="analysis"><a href="#analysis" class="headerlink" title="analysis"></a>analysis</h2><p>一开始就想到了二分查找，但是原来做二分查找的时候一般都是找到确定的那个数就完成了，<br>这里的情况比较特殊，需要找到整个区间，所以需要两遍查找，并且一个是找到小于target<br>的最大索引，一个是找到大于target的最大索引，代码参考<a href="https://discuss.leetcode.com/topic/5891/clean-iterative-solution-with-two-binary-searches-with-explanation/2">leetcode discuss</a>,这位仁<br>兄也做了详细的分析解释。  </p>
<h2 id="code"><a href="#code" class="headerlink" title="code"></a>code</h2><pre class="line-numbers language-C++" data-language="C++"><code class="language-C++">class Solution &#123;
public:
    vector&lt;int&gt; searchRange(vector&lt;int&gt;&amp; nums, int target) &#123;
        vector&lt;int&gt; ret(2, -1);
        int i &#x3D; 0, j &#x3D; nums.size() - 1;
        int mid;
        while(i &lt; j)&#123;
            mid &#x3D; (i + j) &#x2F; 2;
            if(nums[mid] &lt; target) i &#x3D; mid + 1;
            else j &#x3D; mid;
        &#125;
        if(nums[i] !&#x3D; target) return ret;
        else &#123;
            ret[0] &#x3D; i;
            if((i+1) &lt; (nums.size() - 1) &amp;&amp; nums[i+1] &gt; target)&#123;
                ret[1] &#x3D; i;
                return ret;
            &#125;
        &#125;   &#x2F;&#x2F;一点小优化
        j &#x3D; nums.size() - 1;
        while(i &lt; j)&#123;
            mid &#x3D; (i + j) &#x2F; 2 + 1;
            if(nums[mid] &gt; target) j &#x3D; mid - 1;
            else i &#x3D; mid;
        &#125;
        ret[1] &#x3D; j;
        return ret;
    &#125;
&#125;;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>]]></content>
      <categories>
        <category>leetcode</category>
      </categories>
      <tags>
        <tag>leetcode</tag>
        <tag>c++</tag>
      </tags>
  </entry>
  <entry>
    <title>add-two-number</title>
    <url>/2015/04/14/Add-Two-Number/</url>
    <content><![CDATA[<h3 id="problem"><a href="#problem" class="headerlink" title="problem"></a>problem</h3><p>You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.</p>
<p><strong>Input</strong>:<code>(2 -&gt; 4 -&gt; 3) + (5 -&gt; 6 -&gt; 4)</code><br><strong>Output</strong>: <code>7 -&gt; 0 -&gt; 8</code></p>
<p><strong>分析（不用英文装逼了）</strong><br>这个代码是抄来的，<a href="https://github.com/haoel/leetcode">链接</a>原作是这位大大。</p>
<span id="more"></span>
<p>一开始没看懂题，后来发现是要进位的，自己写的时候想把长短不同时长的串接到结果<br>串的后面，试了下因为进位会有些问题比较难搞定，这样的话就是在其中一个为空的<br>时候还是会循环操作，在链表太大的时候可能会有问题，就这样（逃<br>原来是有个小错误没发现，改进后的代码也AC了，棒棒哒！</p>
<h3 id="正确代码"><a href="#正确代码" class="headerlink" title="正确代码"></a>正确代码</h3><pre class="line-numbers language-C++" data-language="C++"><code class="language-C++">&#x2F;**
 * Definition for singly-linked list.
 * struct ListNode &#123;
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) &#123;&#125;
 * &#125;;
 *&#x2F;
class Solution &#123;
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) &#123;
        ListNode dummy(0);
        ListNode* p &#x3D; &amp;dummy;

        int cn &#x3D; 0;
        while(l1 || l2)&#123;
            int val &#x3D; cn + (l1 ? l1-&gt;val : 0) + (l2 ? l2-&gt;val : 0);
            cn &#x3D; val &#x2F; 10;
            val &#x3D; val % 10;
            p-&gt;next &#x3D; new ListNode(val);
            p &#x3D; p-&gt;next;
            if(l1)&#123;
                l1 &#x3D; l1-&gt;next;
            &#125;
            if(l2)&#123;
                l2 &#x3D; l2-&gt;next;
            &#125;
        &#125;
        if(cn !&#x3D; 0)&#123;
            p-&gt;next &#x3D; new ListNode(cn);
            p &#x3D; p-&gt;next;
        &#125;
        return dummy.next;
    &#125;
&#125;;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="失败的代码"><a href="#失败的代码" class="headerlink" title="失败的代码"></a>失败的代码</h3><pre class="line-numbers language-C++" data-language="C++"><code class="language-C++">&#x2F;**
 * Definition for singly-linked list.
 * struct ListNode &#123;
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) &#123;&#125;
 * &#125;;
 *&#x2F;
class Solution &#123;
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) &#123;
        ListNode dummy(0);
        ListNode* p &#x3D; &amp;dummy;

        int cn &#x3D; 0;
        int flag &#x3D; 0;
        while(l1 || l2)&#123;
            int val &#x3D; cn + (l1 ? l1-&gt;val : 0) + (l2 ? l2-&gt;val : 0);
            cn &#x3D; val &#x2F; 10;
            val &#x3D; val % 10;
            p-&gt;next &#x3D; new ListNode(val);
            p &#x3D; p-&gt;next;
            if(!l1 &amp;&amp; cn &#x3D;&#x3D; 0)&#123;
                flag &#x3D; 1;
                break;
            &#125;
            if(!l2 &amp;&amp; cn &#x3D;&#x3D; 0)&#123;
                flag &#x3D; 1;
                break;
            &#125;
            if(l1)&#123;
                l1 &#x3D; l1-&gt;next;
            &#125;
            if(l2)&#123;
                l2 &#x3D; l2-&gt;next;
            &#125;
        &#125;
        if(!l1 &amp;&amp; cn &#x3D;&#x3D; 0 &amp;&amp; flag &#x3D;&#x3D; 1)&#123;
            p-&gt;next &#x3D; l2-&gt;next;
        &#125;
        if(!l2 &amp;&amp; cn &#x3D;&#x3D; 0 &amp;&amp; flag &#x3D;&#x3D; 1)&#123;
            p-&gt;next &#x3D; l1-&gt;next;
        &#125;
        if(cn !&#x3D; 0)&#123;
            p-&gt;next &#x3D; new ListNode(cn);
            p &#x3D; p-&gt;next;
        &#125;
        return dummy.next;
    &#125;
&#125;;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
]]></content>
      <categories>
        <category>leetcode</category>
      </categories>
      <tags>
        <tag>leetcode</tag>
        <tag>c++</tag>
      </tags>
  </entry>
  <entry>
    <title>Apollo 的 value 注解是怎么自动更新的</title>
    <url>/2020/11/01/Apollo-%E7%9A%84-value-%E6%B3%A8%E8%A7%A3%E6%98%AF%E6%80%8E%E4%B9%88%E8%87%AA%E5%8A%A8%E6%9B%B4%E6%96%B0%E7%9A%84/</url>
    <content><![CDATA[<p>在前司和目前公司，用的配置中心都是使用的 Apollo，经过了业界验证，比较强大的配置管理系统，特别是在0.10 后开始支持对使用 value 注解的配置值进行自动更新，今天刚好有个同学问到我，就顺便写篇文章记录下，其实也是借助于 spring 强大的 bean 生命周期管理，可以实现BeanPostProcessor接口，使用postProcessBeforeInitialization方法，来对bean 内部的属性和方法进行判断，是否有 value 注解，如果有就是将它注册到一个 map 中，可以看到这个方法<code>com.ctrip.framework.apollo.spring.annotation.SpringValueProcessor#processField</code></p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Override</span>
  <span class="token keyword">protected</span> <span class="token keyword">void</span> <span class="token function">processField</span><span class="token punctuation">(</span><span class="token class-name">Object</span> bean<span class="token punctuation">,</span> <span class="token class-name">String</span> beanName<span class="token punctuation">,</span> <span class="token class-name">Field</span> field<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token comment">// register @Value on field</span>
    <span class="token class-name">Value</span> value <span class="token operator">=</span> field<span class="token punctuation">.</span><span class="token function">getAnnotation</span><span class="token punctuation">(</span><span class="token class-name">Value</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>value <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
      <span class="token keyword">return</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token class-name">Set</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">></span></span> keys <span class="token operator">=</span> placeholderHelper<span class="token punctuation">.</span><span class="token function">extractPlaceholderKeys</span><span class="token punctuation">(</span>value<span class="token punctuation">.</span><span class="token function">value</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">if</span> <span class="token punctuation">(</span>keys<span class="token punctuation">.</span><span class="token function">isEmpty</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
      <span class="token keyword">return</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">String</span> key <span class="token operator">:</span> keys<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
      <span class="token class-name">SpringValue</span> springValue <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">SpringValue</span><span class="token punctuation">(</span>key<span class="token punctuation">,</span> value<span class="token punctuation">.</span><span class="token function">value</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> bean<span class="token punctuation">,</span> beanName<span class="token punctuation">,</span> field<span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      springValueRegistry<span class="token punctuation">.</span><span class="token function">register</span><span class="token punctuation">(</span>beanFactory<span class="token punctuation">,</span> key<span class="token punctuation">,</span> springValue<span class="token punctuation">)</span><span class="token punctuation">;</span>
      logger<span class="token punctuation">.</span><span class="token function">debug</span><span class="token punctuation">(</span><span class="token string">"Monitoring &#123;&#125;"</span><span class="token punctuation">,</span> springValue<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
  <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>然后我们看下这个<code>springValueRegistry</code>是啥玩意</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">SpringValueRegistry</span> <span class="token punctuation">&#123;</span>
  <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">final</span> <span class="token keyword">long</span> CLEAN_INTERVAL_IN_SECONDS <span class="token operator">=</span> <span class="token number">5</span><span class="token punctuation">;</span>
  <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token class-name">Map</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">BeanFactory</span><span class="token punctuation">,</span> <span class="token class-name">Multimap</span><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">SpringValue</span><span class="token punctuation">></span><span class="token punctuation">></span></span> registry <span class="token operator">=</span> <span class="token class-name">Maps</span><span class="token punctuation">.</span><span class="token function">newConcurrentMap</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token class-name">AtomicBoolean</span> initialized <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">AtomicBoolean</span><span class="token punctuation">(</span><span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token class-name">Object</span> LOCK <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Object</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">register</span><span class="token punctuation">(</span><span class="token class-name">BeanFactory</span> beanFactory<span class="token punctuation">,</span> <span class="token class-name">String</span> key<span class="token punctuation">,</span> <span class="token class-name">SpringValue</span> springValue<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>registry<span class="token punctuation">.</span><span class="token function">containsKey</span><span class="token punctuation">(</span>beanFactory<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
      <span class="token keyword">synchronized</span> <span class="token punctuation">(</span>LOCK<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>registry<span class="token punctuation">.</span><span class="token function">containsKey</span><span class="token punctuation">(</span>beanFactory<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
          registry<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span>beanFactory<span class="token punctuation">,</span> <span class="token class-name">LinkedListMultimap</span><span class="token punctuation">.</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">SpringValue</span><span class="token punctuation">></span></span><span class="token function">create</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
      <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>

    registry<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span>beanFactory<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span>key<span class="token punctuation">,</span> springValue<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token comment">// lazy initialize</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>initialized<span class="token punctuation">.</span><span class="token function">compareAndSet</span><span class="token punctuation">(</span><span class="token boolean">false</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
      <span class="token function">initialize</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
  <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这类其实就是个 map 来存放 springvalue，然后有<code>com.ctrip.framework.apollo.spring.property.AutoUpdateConfigChangeListener</code>来监听更新操作，当有变更时</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Override</span>
 <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">onChange</span><span class="token punctuation">(</span><span class="token class-name">ConfigChangeEvent</span> changeEvent<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
   <span class="token class-name">Set</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">></span></span> keys <span class="token operator">=</span> changeEvent<span class="token punctuation">.</span><span class="token function">changedKeys</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
   <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">CollectionUtils</span><span class="token punctuation">.</span><span class="token function">isEmpty</span><span class="token punctuation">(</span>keys<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
     <span class="token keyword">return</span><span class="token punctuation">;</span>
   <span class="token punctuation">&#125;</span>
   <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">String</span> key <span class="token operator">:</span> keys<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
     <span class="token comment">// 1. check whether the changed key is relevant</span>
     <span class="token class-name">Collection</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">SpringValue</span><span class="token punctuation">></span></span> targetValues <span class="token operator">=</span> springValueRegistry<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span>beanFactory<span class="token punctuation">,</span> key<span class="token punctuation">)</span><span class="token punctuation">;</span>
     <span class="token keyword">if</span> <span class="token punctuation">(</span>targetValues <span class="token operator">==</span> <span class="token keyword">null</span> <span class="token operator">||</span> targetValues<span class="token punctuation">.</span><span class="token function">isEmpty</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
       <span class="token keyword">continue</span><span class="token punctuation">;</span>
     <span class="token punctuation">&#125;</span>

     <span class="token comment">// 2. check whether the value is really changed or not (since spring property sources have hierarchies)</span>
     <span class="token comment">// 这里其实有一点比较绕，是因为 Apollo 里的 namespace 划分，会出现 key 相同，但是 namespace 不同的情况，所以会有个优先级存在，所以需要去校验 environment 里面的是否已经更新，如果未更新则表示不需要更新</span>
     <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token function">shouldTriggerAutoUpdate</span><span class="token punctuation">(</span>changeEvent<span class="token punctuation">,</span> key<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
       <span class="token keyword">continue</span><span class="token punctuation">;</span>
     <span class="token punctuation">&#125;</span>

     <span class="token comment">// 3. update the value</span>
     <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">SpringValue</span> val <span class="token operator">:</span> targetValues<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
       <span class="token function">updateSpringValue</span><span class="token punctuation">(</span>val<span class="token punctuation">)</span><span class="token punctuation">;</span>
     <span class="token punctuation">&#125;</span>
   <span class="token punctuation">&#125;</span>
 <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>其实原理很简单，就是得了解知道下</p>
]]></content>
      <categories>
        <category>Java</category>
        <category>Apollo</category>
        <category>value</category>
      </categories>
      <tags>
        <tag>Java</tag>
        <tag>Apollo</tag>
        <tag>value</tag>
        <tag>注解</tag>
        <tag>environment</tag>
      </tags>
  </entry>
  <entry>
    <title>Clone Graph Part I</title>
    <url>/2014/12/30/Clone-Graph-Part-I/</url>
    <content><![CDATA[<h3 id="problem"><a href="#problem" class="headerlink" title="problem"></a>problem</h3><pre class="line-numbers language-none"><code class="language-none">Clone a graph. Input is a Node pointer. Return the Node pointer of the cloned graph.

A graph is defined below:
struct Node &#123;
vector neighbors;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<span id="more"></span>
<h3 id="code"><a href="#code" class="headerlink" title="code"></a>code</h3><pre class="line-numbers language-c++" data-language="c++"><code class="language-c++">typedef unordered_map&lt;Node *, Node *&gt; Map;
 
Node *clone(Node *graph) &#123;
    if (!graph) return NULL;
 
    Map map;
    queue&lt;Node *&gt; q;
    q.push(graph);
 
    Node *graphCopy &#x3D; new Node();
    map[graph] &#x3D; graphCopy;
 
    while (!q.empty()) &#123;
        Node *node &#x3D; q.front();
        q.pop();
        int n &#x3D; node-&gt;neighbors.size();
        for (int i &#x3D; 0; i &lt; n; i++) &#123;
            Node *neighbor &#x3D; node-&gt;neighbors[i];
            &#x2F;&#x2F; no copy exists
            if (map.find(neighbor) &#x3D;&#x3D; map.end()) &#123;
                Node *p &#x3D; new Node();
                map[node]-&gt;neighbors.push_back(p);
                map[neighbor] &#x3D; p;
                q.push(neighbor);
            &#125; else &#123;     &#x2F;&#x2F; a copy already exists
                map[node]-&gt;neighbors.push_back(map[neighbor]);
            &#125;
        &#125;
    &#125;
 
    return graphCopy;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="anlysis"><a href="#anlysis" class="headerlink" title="anlysis"></a>anlysis</h3><p>using the Breadth-first traversal<br>and use a map to save the neighbors not to be duplicated.</p>
]]></content>
      <categories>
        <category>leetcode</category>
      </categories>
      <tags>
        <tag>C++</tag>
        <tag>leetcode</tag>
      </tags>
  </entry>
  <entry>
    <title>AbstractQueuedSynchronizer</title>
    <url>/2019/09/23/AbstractQueuedSynchronizer/</url>
    <content><![CDATA[<p>最近看了大神的 AQS 的文章，之前总是断断续续地看一点，每次都知难而退，下次看又从头开始，昨天总算硬着头皮看完了第一部分<br>首先 AQS 只要有这些属性</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">// 头结点，你直接把它当做 当前持有锁的线程 可能是最好理解的</span>
<span class="token keyword">private</span> <span class="token keyword">transient</span> <span class="token keyword">volatile</span> <span class="token class-name">Node</span> head<span class="token punctuation">;</span>

<span class="token comment">// 阻塞的尾节点，每个新的节点进来，都插入到最后，也就形成了一个链表</span>
<span class="token keyword">private</span> <span class="token keyword">transient</span> <span class="token keyword">volatile</span> <span class="token class-name">Node</span> tail<span class="token punctuation">;</span>

<span class="token comment">// 这个是最重要的，代表当前锁的状态，0代表没有被占用，大于 0 代表有线程持有当前锁</span>
<span class="token comment">// 这个值可以大于 1，是因为锁可以重入，每次重入都加上 1</span>
<span class="token keyword">private</span> <span class="token keyword">volatile</span> <span class="token keyword">int</span> state<span class="token punctuation">;</span>

<span class="token comment">// 代表当前持有独占锁的线程，举个最重要的使用例子，因为锁可以重入</span>
<span class="token comment">// reentrantLock.lock()可以嵌套调用多次，所以每次用这个来判断当前线程是否已经拥有了锁</span>
<span class="token comment">// if (currentThread == getExclusiveOwnerThread()) &#123;state++&#125;</span>
<span class="token keyword">private</span> <span class="token keyword">transient</span> <span class="token class-name">Thread</span> exclusiveOwnerThread<span class="token punctuation">;</span> <span class="token comment">//继承自AbstractOwnableSynchronizer</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>大概了解了 aqs 底层的双向等待队列，<br>结构是这样的<br><img data-src="https://tva1.sinaimg.cn/large/006tNbRwly1g9mxu0ndt1j319o08w0t7.jpg"><br>每个 node 里面主要是的代码结构也比较简单</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">static</span> <span class="token keyword">final</span> <span class="token keyword">class</span> <span class="token class-name">Node</span> <span class="token punctuation">&#123;</span>
    <span class="token comment">// 标识节点当前在共享模式下</span>
    <span class="token keyword">static</span> <span class="token keyword">final</span> <span class="token class-name">Node</span> SHARED <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Node</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">// 标识节点当前在独占模式下</span>
    <span class="token keyword">static</span> <span class="token keyword">final</span> <span class="token class-name">Node</span> EXCLUSIVE <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>

    <span class="token comment">// ======== 下面的几个int常量是给waitStatus用的 ===========</span>
    <span class="token comment">/** waitStatus value to indicate thread has cancelled */</span>
    <span class="token comment">// 代码此线程取消了争抢这个锁</span>
    <span class="token keyword">static</span> <span class="token keyword">final</span> <span class="token keyword">int</span> CANCELLED <span class="token operator">=</span>  <span class="token number">1</span><span class="token punctuation">;</span>
    <span class="token comment">/** waitStatus value to indicate successor's thread needs unparking */</span>
    <span class="token comment">// 官方的描述是，其表示当前node的后继节点对应的线程需要被唤醒</span>
    <span class="token keyword">static</span> <span class="token keyword">final</span> <span class="token keyword">int</span> SIGNAL    <span class="token operator">=</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">;</span>
    <span class="token comment">/** waitStatus value to indicate thread is waiting on condition */</span>
    <span class="token comment">// 本文不分析condition，所以略过吧，下一篇文章会介绍这个</span>
    <span class="token keyword">static</span> <span class="token keyword">final</span> <span class="token keyword">int</span> CONDITION <span class="token operator">=</span> <span class="token operator">-</span><span class="token number">2</span><span class="token punctuation">;</span>
    <span class="token comment">/**
     * waitStatus value to indicate the next acquireShared should
     * unconditionally propagate
     */</span>
    <span class="token comment">// 同样的不分析，略过吧</span>
    <span class="token keyword">static</span> <span class="token keyword">final</span> <span class="token keyword">int</span> PROPAGATE <span class="token operator">=</span> <span class="token operator">-</span><span class="token number">3</span><span class="token punctuation">;</span>
    <span class="token comment">// =====================================================</span>


    <span class="token comment">// 取值为上面的1、-1、-2、-3，或者0(以后会讲到)</span>
    <span class="token comment">// 这么理解，暂时只需要知道如果这个值 大于0 代表此线程取消了等待，</span>
    <span class="token comment">//    ps: 半天抢不到锁，不抢了，ReentrantLock是可以指定timeouot的。。。</span>
    <span class="token keyword">volatile</span> <span class="token keyword">int</span> waitStatus<span class="token punctuation">;</span>
    <span class="token comment">// 前驱节点的引用</span>
    <span class="token keyword">volatile</span> <span class="token class-name">Node</span> prev<span class="token punctuation">;</span>
    <span class="token comment">// 后继节点的引用</span>
    <span class="token keyword">volatile</span> <span class="token class-name">Node</span> next<span class="token punctuation">;</span>
    <span class="token comment">// 这个就是线程本尊</span>
    <span class="token keyword">volatile</span> <span class="token class-name">Thread</span> thread<span class="token punctuation">;</span>

<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>其实可以主要关注这个 <code>waitStatus</code> 因为这个是后面的节点给前面的节点设置的，等于-1 的时候代表后面有节点等待，需要去唤醒，<br>这里使用了一个变种的 CLH 队列实现，CLH 队列相关内容可以查看这篇 <a href="https://coderbee.net/index.php/concurrent/20131115/577">自旋锁、排队自旋锁、MCS锁、CLH锁</a></p>
]]></content>
      <categories>
        <category>java</category>
      </categories>
      <tags>
        <tag>java</tag>
        <tag>aqs</tag>
      </tags>
  </entry>
  <entry>
    <title>Comparator使用小记</title>
    <url>/2020/04/05/Comparator%E4%BD%BF%E7%94%A8%E5%B0%8F%E8%AE%B0/</url>
    <content><![CDATA[<p>在Java8的stream之前，将对象进行排序的时候，可能需要对象实现Comparable接口，或者自己实现一个Comparator，</p>
<p>比如这样子</p>
<p>我的对象是Entity</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Entity</span> <span class="token punctuation">&#123;</span>

    <span class="token keyword">private</span> <span class="token class-name">Long</span> id<span class="token punctuation">;</span>

    <span class="token keyword">private</span> <span class="token class-name">Long</span> sortValue<span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token class-name">Long</span> <span class="token function">getId</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> id<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">setId</span><span class="token punctuation">(</span><span class="token class-name">Long</span> id<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>id <span class="token operator">=</span> id<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token class-name">Long</span> <span class="token function">getSortValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> sortValue<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">setSortValue</span><span class="token punctuation">(</span><span class="token class-name">Long</span> sortValue<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>sortValue <span class="token operator">=</span> sortValue<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>Comparator</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">MyComparator</span> <span class="token keyword">implements</span> <span class="token class-name">Comparator</span> <span class="token punctuation">&#123;</span>
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">compare</span><span class="token punctuation">(</span><span class="token class-name">Object</span> o1<span class="token punctuation">,</span> <span class="token class-name">Object</span> o2<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">Entity</span> e1 <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">Entity</span><span class="token punctuation">)</span> o1<span class="token punctuation">;</span>
        <span class="token class-name">Entity</span> e2 <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">Entity</span><span class="token punctuation">)</span> o2<span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>e1<span class="token punctuation">.</span><span class="token function">getSortValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&lt;</span> e2<span class="token punctuation">.</span><span class="token function">getSortValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>e1<span class="token punctuation">.</span><span class="token function">getSortValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>e2<span class="token punctuation">.</span><span class="token function">getSortValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> <span class="token number">1</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>比较代码</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token class-name">MyComparator</span> myComparator <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">MyComparator</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Entity</span><span class="token punctuation">></span></span> list <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayList</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Entity</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Entity</span> e1 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Entity</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        e1<span class="token punctuation">.</span><span class="token function">setId</span><span class="token punctuation">(</span><span class="token number">1L</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        e1<span class="token punctuation">.</span><span class="token function">setSortValue</span><span class="token punctuation">(</span><span class="token number">1L</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        list<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>e1<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Entity</span> e2 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Entity</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        e2<span class="token punctuation">.</span><span class="token function">setId</span><span class="token punctuation">(</span><span class="token number">2L</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        e2<span class="token punctuation">.</span><span class="token function">setSortValue</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        list<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>e2<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Collections</span><span class="token punctuation">.</span><span class="token function">sort</span><span class="token punctuation">(</span>list<span class="token punctuation">,</span> myComparator<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>看到这里的e2的排序值是null，在Comparator中如果要正常运行的话，就得判空之类的，这里有两点需要，一个是不想写这个MyComparator，然后也没那么好排除掉list里排序值，那么有什么办法能解决这种问题呢，应该说java的这方面真的是很强大</p>
<p><img data-src="https://i.loli.net/2020/04/05/8VfjeOSmcvx4dyk.png"></p>
<p>看一下nullsFirst的实现</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">final</span> <span class="token keyword">static</span> <span class="token keyword">class</span> <span class="token class-name">NullComparator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">></span></span> <span class="token keyword">implements</span> <span class="token class-name">Comparator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">></span></span><span class="token punctuation">,</span> <span class="token class-name">Serializable</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">final</span> <span class="token keyword">long</span> serialVersionUID <span class="token operator">=</span> <span class="token operator">-</span><span class="token number">7569533591570686392L</span><span class="token punctuation">;</span>
        <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token keyword">boolean</span> nullFirst<span class="token punctuation">;</span>
        <span class="token comment">// if null, non-null Ts are considered equal</span>
        <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token class-name">Comparator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">></span></span> real<span class="token punctuation">;</span>

        <span class="token annotation punctuation">@SuppressWarnings</span><span class="token punctuation">(</span><span class="token string">"unchecked"</span><span class="token punctuation">)</span>
        <span class="token class-name">NullComparator</span><span class="token punctuation">(</span><span class="token keyword">boolean</span> nullFirst<span class="token punctuation">,</span> <span class="token class-name">Comparator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span> <span class="token keyword">super</span> <span class="token class-name">T</span><span class="token punctuation">></span></span> real<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>nullFirst <span class="token operator">=</span> nullFirst<span class="token punctuation">;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>real <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">Comparator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">></span></span><span class="token punctuation">)</span> real<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token annotation punctuation">@Override</span>
        <span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">compare</span><span class="token punctuation">(</span><span class="token class-name">T</span> a<span class="token punctuation">,</span> <span class="token class-name">T</span> b<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>a <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">return</span> <span class="token punctuation">(</span>b <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token operator">?</span> <span class="token number">0</span> <span class="token operator">:</span> <span class="token punctuation">(</span>nullFirst <span class="token operator">?</span> <span class="token operator">-</span><span class="token number">1</span> <span class="token operator">:</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>b <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">return</span> nullFirst <span class="token operator">?</span> <span class="token number">1</span><span class="token operator">:</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">return</span> <span class="token punctuation">(</span>real <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token operator">?</span> <span class="token number">0</span> <span class="token operator">:</span> real<span class="token punctuation">.</span><span class="token function">compare</span><span class="token punctuation">(</span>a<span class="token punctuation">,</span> b<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>核心代码就是下面这段，其实就是帮我们把前面要做的事情做掉了，是不是挺方便的，小记一下哈</p>
]]></content>
      <categories>
        <category>Java</category>
        <category>集合</category>
      </categories>
      <tags>
        <tag>Java</tag>
        <tag>Stream</tag>
        <tag>Comparator</tag>
        <tag>排序</tag>
        <tag>sort</tag>
        <tag>nullsfirst</tag>
      </tags>
  </entry>
  <entry>
    <title>AQS篇一</title>
    <url>/2021/02/14/AQS%E7%AF%87%E4%B8%80/</url>
    <content><![CDATA[<p>很多东西都是时看时新，而且时间长了也会忘，所以再来复习下，也会有一些新的角度看法这次来聊下AQS的内容，主要是这几个点，</p>
<h2 id="第一个线程"><a href="#第一个线程" class="headerlink" title="第一个线程"></a>第一个线程</h2><p>第一个线程抢到锁了，此时state跟阻塞队列是怎么样的，其实这里是之前没理解对的地方</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">/**
         * Fair version of tryAcquire.  Don't grant access unless
         * recursive call or no waiters or is first.
         */</span>
        <span class="token keyword">protected</span> <span class="token keyword">final</span> <span class="token keyword">boolean</span> <span class="token function">tryAcquire</span><span class="token punctuation">(</span><span class="token keyword">int</span> acquires<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">final</span> <span class="token class-name">Thread</span> current <span class="token operator">=</span> <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">int</span> c <span class="token operator">=</span> <span class="token function">getState</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token comment">// 这里如果state还是0说明锁还空着</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>c <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token comment">// 因为是公平锁版本的，先去看下是否阻塞队列里有排着队的</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token function">hasQueuedPredecessors</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span>
                    <span class="token function">compareAndSetState</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> acquires<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token comment">// 没有排队的，并且state使用cas设置成功的就标记当前占有锁的线程是我</span>
                    <span class="token function">setExclusiveOwnerThread</span><span class="token punctuation">(</span>current<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token comment">// 然后其实就返回了，包括阻塞队列的head和tail节点和waitStatus都没有设置</span>
                    <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span>
            <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>current <span class="token operator">==</span> <span class="token function">getExclusiveOwnerThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">int</span> nextc <span class="token operator">=</span> c <span class="token operator">+</span> acquires<span class="token punctuation">;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>nextc <span class="token operator">&lt;</span> <span class="token number">0</span><span class="token punctuation">)</span>
                    <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">Error</span><span class="token punctuation">(</span><span class="token string">"Maximum lock count exceeded"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token function">setState</span><span class="token punctuation">(</span>nextc<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
            <span class="token comment">// 这里就是第二个线程会返回false</span>
            <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="第二个线程"><a href="#第二个线程" class="headerlink" title="第二个线程"></a>第二个线程</h2><p>当第二个线程进来的时候应该是怎么样，结合代码来看</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">/**
     * Acquires in exclusive mode, ignoring interrupts.  Implemented
     * by invoking at least once &#123;@link #tryAcquire&#125;,
     * returning on success.  Otherwise the thread is queued, possibly
     * repeatedly blocking and unblocking, invoking &#123;@link
     * #tryAcquire&#125; until success.  This method can be used
     * to implement method &#123;@link Lock#lock&#125;.
     *
     * @param arg the acquire argument.  This value is conveyed to
     *        &#123;@link #tryAcquire&#125; but is otherwise uninterpreted and
     *        can represent anything you like.
     */</span>
    <span class="token keyword">public</span> <span class="token keyword">final</span> <span class="token keyword">void</span> <span class="token function">acquire</span><span class="token punctuation">(</span><span class="token keyword">int</span> arg<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">// 前面第一种情况是tryAcquire直接成功了，这个if判断第一个条件就是false，就不往下执行了</span>
        <span class="token comment">// 如果是第二个线程，第一个条件获取锁不成功，条件判断!tryAcquire(arg) == true，就会走</span>
        <span class="token comment">// acquireQueued(addWaiter(Node.EXCLUSIVE), arg)</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token function">tryAcquire</span><span class="token punctuation">(</span>arg<span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span>
            <span class="token function">acquireQueued</span><span class="token punctuation">(</span><span class="token function">addWaiter</span><span class="token punctuation">(</span><span class="token class-name">Node</span><span class="token punctuation">.</span>EXCLUSIVE<span class="token punctuation">)</span><span class="token punctuation">,</span> arg<span class="token punctuation">)</span><span class="token punctuation">)</span>
            <span class="token function">selfInterrupt</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>然后来看下addWaiter的逻辑</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">/**
     * Creates and enqueues node for current thread and given mode.
     *
     * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared
     * @return the new node
     */</span>
    <span class="token keyword">private</span> <span class="token class-name">Node</span> <span class="token function">addWaiter</span><span class="token punctuation">(</span><span class="token class-name">Node</span> mode<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">// 这里是包装成一个node</span>
        <span class="token class-name">Node</span> node <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Node</span><span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> mode<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">// Try the fast path of enq; backup to full enq on failure</span>
        <span class="token comment">// 最快的方式就是把当前线程的节点放在阻塞队列的最后</span>
        <span class="token class-name">Node</span> pred <span class="token operator">=</span> tail<span class="token punctuation">;</span>
        <span class="token comment">// 只有当tail，也就是pred不为空的时候可以直接接上</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>pred <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            node<span class="token punctuation">.</span>prev <span class="token operator">=</span> pred<span class="token punctuation">;</span>
            <span class="token comment">// 如果这里cas成功了，就直接接上返回了</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">compareAndSetTail</span><span class="token punctuation">(</span>pred<span class="token punctuation">,</span> node<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                pred<span class="token punctuation">.</span>next <span class="token operator">=</span> node<span class="token punctuation">;</span>
                <span class="token keyword">return</span> node<span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token comment">// 不然就会继续走到这里</span>
        <span class="token function">enq</span><span class="token punctuation">(</span>node<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> node<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>然后就是enq的逻辑了</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">/**
     * Inserts node into queue, initializing if necessary. See picture above.
     * @param node the node to insert
     * @return node's predecessor
     */</span>
    <span class="token keyword">private</span> <span class="token class-name">Node</span> <span class="token function">enq</span><span class="token punctuation">(</span><span class="token keyword">final</span> <span class="token class-name">Node</span> node<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token punctuation">;</span><span class="token punctuation">;</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token comment">// 如果状态没变化的话，tail这时还是null的</span>
            <span class="token class-name">Node</span> t <span class="token operator">=</span> tail<span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>t <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span> <span class="token comment">// Must initialize</span>
                <span class="token comment">// 这里就会初始化头结点，就是个空节点</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">compareAndSetHead</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Node</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
                    <span class="token comment">// tail也赋值成head</span>
                    tail <span class="token operator">=</span> head<span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                <span class="token comment">// 这里就设置tail了</span>
                node<span class="token punctuation">.</span>prev <span class="token operator">=</span> t<span class="token punctuation">;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">compareAndSetTail</span><span class="token punctuation">(</span>t<span class="token punctuation">,</span> node<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    t<span class="token punctuation">.</span>next <span class="token operator">=</span> node<span class="token punctuation">;</span>
                    <span class="token keyword">return</span> t<span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>所以从这里可以看出来，其实head头结点不是个真实的带有线程的节点，并且不是在第一个线程进来的时候设置的</p>
<h2 id="解锁"><a href="#解锁" class="headerlink" title="解锁"></a>解锁</h2><p>通过代码来看下</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">/**
     * Attempts to release this lock.
     *
     * &lt;p>If the current thread is the holder of this lock then the hold
     * count is decremented.  If the hold count is now zero then the lock
     * is released.  If the current thread is not the holder of this
     * lock then &#123;@link IllegalMonitorStateException&#125; is thrown.
     *
     * @throws IllegalMonitorStateException if the current thread does not
     *         hold this lock
     */</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">// 释放锁</span>
        sync<span class="token punctuation">.</span><span class="token function">release</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token comment">/**
     * Releases in exclusive mode.  Implemented by unblocking one or
     * more threads if &#123;@link #tryRelease&#125; returns true.
     * This method can be used to implement method &#123;@link Lock#unlock&#125;.
     *
     * @param arg the release argument.  This value is conveyed to
     *        &#123;@link #tryRelease&#125; but is otherwise uninterpreted and
     *        can represent anything you like.
     * @return the value returned from &#123;@link #tryRelease&#125;
     */</span>
    <span class="token keyword">public</span> <span class="token keyword">final</span> <span class="token keyword">boolean</span> <span class="token function">release</span><span class="token punctuation">(</span><span class="token keyword">int</span> arg<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">// 尝试去释放</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">tryRelease</span><span class="token punctuation">(</span>arg<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">Node</span> h <span class="token operator">=</span> head<span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>h <span class="token operator">!=</span> <span class="token keyword">null</span> <span class="token operator">&amp;&amp;</span> h<span class="token punctuation">.</span>waitStatus <span class="token operator">!=</span> <span class="token number">0</span><span class="token punctuation">)</span>
                <span class="token function">unparkSuccessor</span><span class="token punctuation">(</span>h<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token keyword">protected</span> <span class="token keyword">final</span> <span class="token keyword">boolean</span> <span class="token function">tryRelease</span><span class="token punctuation">(</span><span class="token keyword">int</span> releases<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">int</span> c <span class="token operator">=</span> <span class="token function">getState</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-</span> releases<span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">!=</span> <span class="token function">getExclusiveOwnerThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
                <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">IllegalMonitorStateException</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">boolean</span> free <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
    		<span class="token comment">// 判断是否完全释放锁，因为可重入</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>c <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                free <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
                <span class="token function">setExclusiveOwnerThread</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
            <span class="token function">setState</span><span class="token punctuation">(</span>c<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">return</span> free<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
<span class="token comment">// 这段代码和上面的一致，只是为了顺序性，又拷下来看下</span>

<span class="token keyword">public</span> <span class="token keyword">final</span> <span class="token keyword">boolean</span> <span class="token function">release</span><span class="token punctuation">(</span><span class="token keyword">int</span> arg<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">// 尝试去释放，如果是完全释放，返回的就是true，否则是false</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">tryRelease</span><span class="token punctuation">(</span>arg<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">Node</span> h <span class="token operator">=</span> head<span class="token punctuation">;</span>
            <span class="token comment">// 这里判断头结点是否为空以及waitStatus的状态，前面说了head节点其实是</span>
            <span class="token comment">// 在第二个线程进来的时候初始化的，如果是空的话说明没后续节点，并且waitStatus</span>
            <span class="token comment">// 也表示了后续的等待状态</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>h <span class="token operator">!=</span> <span class="token keyword">null</span> <span class="token operator">&amp;&amp;</span> h<span class="token punctuation">.</span>waitStatus <span class="token operator">!=</span> <span class="token number">0</span><span class="token punctuation">)</span>
                <span class="token function">unparkSuccessor</span><span class="token punctuation">(</span>h<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

<span class="token comment">/**
     * Wakes up node's successor, if one exists.
     *
     * @param node the node
     */</span>
<span class="token comment">// 唤醒后继节点</span>
    <span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">unparkSuccessor</span><span class="token punctuation">(</span><span class="token class-name">Node</span> node<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">/*
         * If status is negative (i.e., possibly needing signal) try
         * to clear in anticipation of signalling.  It is OK if this
         * fails or if status is changed by waiting thread.
         */</span>
        <span class="token keyword">int</span> ws <span class="token operator">=</span> node<span class="token punctuation">.</span>waitStatus<span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>ws <span class="token operator">&lt;</span> <span class="token number">0</span><span class="token punctuation">)</span>
            <span class="token function">compareAndSetWaitStatus</span><span class="token punctuation">(</span>node<span class="token punctuation">,</span> ws<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment">/*
         * Thread to unpark is held in successor, which is normally
         * just the next node.  But if cancelled or apparently null,
         * traverse backwards from tail to find the actual
         * non-cancelled successor.
         */</span>
        <span class="token class-name">Node</span> s <span class="token operator">=</span> node<span class="token punctuation">.</span>next<span class="token punctuation">;</span>
        <span class="token comment">// 如果后继节点是空或者当前节点取消等待了</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>s <span class="token operator">==</span> <span class="token keyword">null</span> <span class="token operator">||</span> s<span class="token punctuation">.</span>waitStatus <span class="token operator">></span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            s <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
            <span class="token comment">// 从后往前找，找到非取消的节点，注意这里不是找到就退出，而是一直找到头</span>
            <span class="token comment">// 所以不必担心中间有取消的</span>
            <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">Node</span> t <span class="token operator">=</span> tail<span class="token punctuation">;</span> t <span class="token operator">!=</span> <span class="token keyword">null</span> <span class="token operator">&amp;&amp;</span> t <span class="token operator">!=</span> node<span class="token punctuation">;</span> t <span class="token operator">=</span> t<span class="token punctuation">.</span>prev<span class="token punctuation">)</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>t<span class="token punctuation">.</span>waitStatus <span class="token operator">&lt;=</span> <span class="token number">0</span><span class="token punctuation">)</span>
                    s <span class="token operator">=</span> t<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>s <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span>
            <span class="token comment">// 将其唤醒</span>
            <span class="token class-name">LockSupport</span><span class="token punctuation">.</span><span class="token function">unpark</span><span class="token punctuation">(</span>s<span class="token punctuation">.</span>thread<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>




]]></content>
      <categories>
        <category>Java</category>
        <category>并发</category>
      </categories>
      <tags>
        <tag>java</tag>
        <tag>aqs</tag>
        <tag>并发</tag>
        <tag>j.u.c</tag>
      </tags>
  </entry>
  <entry>
    <title>G1收集器概述</title>
    <url>/2020/02/09/G1%E6%94%B6%E9%9B%86%E5%99%A8%E6%A6%82%E8%BF%B0/</url>
    <content><![CDATA[<p>G1: The Garbage-First Collector, 垃圾回收优先的垃圾回收器，目标是用户多核 cpu 和大内存的机器，最大的特点就是可预测的停顿时间，官方给出的介绍是提供一个用户在大的堆内存情况下一个低延迟表现的解决方案，通常是 6GB 及以上的堆大小，有低于 0.5 秒稳定的可预测的停顿时间。</p>
<p>这里主要介绍这个比较新的垃圾回收器，在 G1 之前的垃圾回收器都是基于如下图的内存结构分布，有新生代，老年代和永久代（jdk8 之前），然后G1 往前的那些垃圾回收器都有个分代，比如 serial，parallel 等，一般有个应用的组合，最初的 serial 和 serial old，因为新生代和老年代的收集方式不太一样，新生代主要是标记复制，所以有 eden 跟两个 survival区，老年代一般用标记整理方式，而 G1 对这个不太一样。<br><img data-src="https://i.loli.net/2020/02/09/jOVs2AlphzwyF5c.jpg"><br>看一下 G1 的内存分布<br><img data-src="https://i.loli.net/2020/02/09/Yr1tGiWp4mAZSzB.jpg"><br>可以看到这有很大的不同，G1 通过将内存分成大小相等的 region，每个region是存在于一个连续的虚拟内存范围，对于某个 region 来说其角色是类似于原来的收集器的Eden、Survivor、Old Generation，这个具体在代码层面</p>
<pre class="line-numbers language-c++" data-language="c++"><code class="language-c++">&#x2F;&#x2F; We encode the value of the heap region type so the generation can be
 &#x2F;&#x2F; determined quickly. The tag is split into two parts:
 &#x2F;&#x2F;
 &#x2F;&#x2F;   major type (young, old, humongous, archive)           : top N-1 bits
 &#x2F;&#x2F;   minor type (eden &#x2F; survivor, starts &#x2F; cont hum, etc.) : bottom 1 bit
 &#x2F;&#x2F;
 &#x2F;&#x2F; If there&#39;s need to increase the number of minor types in the
 &#x2F;&#x2F; future, we&#39;ll have to increase the size of the latter and hence
 &#x2F;&#x2F; decrease the size of the former.
 &#x2F;&#x2F;
 &#x2F;&#x2F; 00000 0 [ 0] Free
 &#x2F;&#x2F;
 &#x2F;&#x2F; 00001 0 [ 2] Young Mask
 &#x2F;&#x2F; 00001 0 [ 2] Eden
 &#x2F;&#x2F; 00001 1 [ 3] Survivor
 &#x2F;&#x2F;
 &#x2F;&#x2F; 00010 0 [ 4] Humongous Mask
 &#x2F;&#x2F; 00100 0 [ 8] Pinned Mask
 &#x2F;&#x2F; 00110 0 [12] Starts Humongous
 &#x2F;&#x2F; 00110 1 [13] Continues Humongous
 &#x2F;&#x2F;
 &#x2F;&#x2F; 01000 0 [16] Old Mask
 &#x2F;&#x2F;
 &#x2F;&#x2F; 10000 0 [32] Archive Mask
 &#x2F;&#x2F; 11100 0 [56] Open Archive
 &#x2F;&#x2F; 11100 1 [57] Closed Archive
 &#x2F;&#x2F;
 typedef enum &#123;
   FreeTag               &#x3D; 0,

   YoungMask             &#x3D; 2,
   EdenTag               &#x3D; YoungMask,
   SurvTag               &#x3D; YoungMask + 1,

   HumongousMask         &#x3D; 4,
   PinnedMask            &#x3D; 8,
   StartsHumongousTag    &#x3D; HumongousMask | PinnedMask,
   ContinuesHumongousTag &#x3D; HumongousMask | PinnedMask + 1,

   OldMask               &#x3D; 16,
   OldTag                &#x3D; OldMask,

   &#x2F;&#x2F; Archive regions are regions with immutable content (i.e. not reclaimed, and
   &#x2F;&#x2F; not allocated into during regular operation). They differ in the kind of references
   &#x2F;&#x2F; allowed for the contained objects:
   &#x2F;&#x2F; - Closed archive regions form a separate self-contained (closed) object graph
   &#x2F;&#x2F; within the set of all of these regions. No references outside of closed
   &#x2F;&#x2F; archive regions are allowed.
   &#x2F;&#x2F; - Open archive regions have no restrictions on the references of their objects.
   &#x2F;&#x2F; Objects within these regions are allowed to have references to objects
   &#x2F;&#x2F; contained in any other kind of regions.
   ArchiveMask           &#x3D; 32,
   OpenArchiveTag        &#x3D; ArchiveMask | PinnedMask | OldMask,
   ClosedArchiveTag      &#x3D; ArchiveMask | PinnedMask | OldMask + 1
 &#125; Tag;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><code>hotspot/share/gc/g1/heapRegionType.hpp</code></p>
<p>当执行垃圾收集时，G1以类似于CMS收集器的方式运行。 G1执行并发全局标记阶段，以确定整个堆中对象的存活性。标记阶段完成后，G1知道哪些region是基本空的。它首先收集这些region，通常会产生大量的可用空间。这就是为什么这种垃圾收集方法称为“垃圾优先”的原因。顾名思义，G1将其收集和压缩活动集中在可能充满可回收对象（即垃圾）的堆区域。 G1使用暂停预测模型来满足用户定义的暂停时间目标，并根据指定的暂停时间目标选择要收集的区域数。</p>
<p>由G1标识为可回收的区域是使用撤离的方式(Evacuation)。 G1将对象从堆的一个或多个区域复制到堆上的单个区域，并在此过程中压缩并释放内存。撤离是在多处理器上并行执行的，以减少暂停时间并增加吞吐量。因此，对于每次垃圾收集，G1都在用户定义的暂停时间内连续工作以减少碎片。这是优于前面两种方法的。 CMS（并发标记扫描）垃圾收集器不进行压缩。 ParallelOld垃圾回收仅执行整个堆压缩，这导致相当长的暂停时间。</p>
<p>需要重点注意的是，G1不是实时收集器。它很有可能达到设定的暂停时间目标，但并非绝对确定。 G1根据先前收集的数据，估算在用户指定的目标时间内可以收集多少个区域。因此，收集器具有收集区域成本的合理准确的模型，并且收集器使用此模型来确定要收集哪些和多少个区域，同时保持在暂停时间目标之内。</p>
<p>注意：G1同时具有并发（与应用程序线程一起运行，例如优化，标记，清理）和并行（多线程，例如stw）阶段。Full GC仍然是单线程的，但是如果正确调优，您的应用程序应该可以避免Full GC。</p>
<p>在前面那篇中在代码层面简单的了解了这个可预测时间的过程，这也是 G1 的一大特点。</p>
]]></content>
      <categories>
        <category>Java</category>
        <category>JVM</category>
        <category>GC</category>
        <category>C++</category>
      </categories>
      <tags>
        <tag>Java</tag>
        <tag>JVM</tag>
        <tag>C++</tag>
        <tag>G1</tag>
        <tag>GC</tag>
        <tag>Garbage-First Collector</tag>
      </tags>
  </entry>
  <entry>
    <title>Leetcode 021 合并两个有序链表 ( Merge Two Sorted Lists ) 题解分析</title>
    <url>/2021/10/07/Leetcode-021-%E5%90%88%E5%B9%B6%E4%B8%A4%E4%B8%AA%E6%9C%89%E5%BA%8F%E9%93%BE%E8%A1%A8-Merge-Two-Sorted-Lists-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/</url>
    <content><![CDATA[<h3 id="题目介绍"><a href="#题目介绍" class="headerlink" title="题目介绍"></a>题目介绍</h3><p>Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.</p>
<p>将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 </p>
<h4 id="示例-1"><a href="#示例-1" class="headerlink" title="示例 1"></a>示例 1</h4><p><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/R1wHlz.jpg"></p>
<blockquote>
<p><strong>输入</strong>：l1 = [1,2,4], l2 = [1,3,4]<br><strong>输出</strong>：[1,1,2,3,4,4]</p>
</blockquote>
<h4 id="示例-2"><a href="#示例-2" class="headerlink" title="示例 2"></a>示例 2</h4><blockquote>
<p><strong>输入</strong>: l1 = [], l2 = []<br><strong>输出</strong>: []</p>
</blockquote>
<h4 id="示例-3"><a href="#示例-3" class="headerlink" title="示例 3"></a>示例 3</h4><blockquote>
<p><strong>输入</strong>: l1 = [], l2 = [0]<br><strong>输出</strong>: [0]</p>
</blockquote>
<h3 id="简要分析"><a href="#简要分析" class="headerlink" title="简要分析"></a>简要分析</h3><p>这题是 Easy 的，看着也挺简单，两个链表进行合并，就是比较下大小，可能将就点的话最好就在两个链表中原地合并</p>
<h3 id="题解代码"><a href="#题解代码" class="headerlink" title="题解代码"></a>题解代码</h3><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">ListNode</span> <span class="token function">mergeTwoLists</span><span class="token punctuation">(</span><span class="token class-name">ListNode</span> l1<span class="token punctuation">,</span> <span class="token class-name">ListNode</span> l2<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">// 下面两个if判断了入参的边界，如果其一为null，直接返回另一个就可以了</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>l1 <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> l2<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>l2 <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> l1<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token comment">// new 一个合并后的头结点</span>
        <span class="token class-name">ListNode</span> merged <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ListNode</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">// 这个是当前节点</span>
        <span class="token class-name">ListNode</span> current <span class="token operator">=</span> merged<span class="token punctuation">;</span>
        <span class="token comment">// 一开始给这个while加了l1和l2不全为null的条件，后面想了下不需要</span>
        <span class="token comment">// 因为内部前两个if就是跳出条件</span>
        <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>l1 <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token comment">// 这里其实跟开头类似，只不过这里需要将l2剩余部分接到merged链表后面</span>
                <span class="token comment">// 所以不能是直接current = l2，这样就是把后面的直接丢了</span>
                current<span class="token punctuation">.</span>val <span class="token operator">=</span> l2<span class="token punctuation">.</span>val<span class="token punctuation">;</span>
                current<span class="token punctuation">.</span>next <span class="token operator">=</span> l2<span class="token punctuation">.</span>next<span class="token punctuation">;</span>
                <span class="token keyword">break</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>l2 <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                current<span class="token punctuation">.</span>val <span class="token operator">=</span> l1<span class="token punctuation">.</span>val<span class="token punctuation">;</span>
                current<span class="token punctuation">.</span>next <span class="token operator">=</span> l1<span class="token punctuation">.</span>next<span class="token punctuation">;</span>
                <span class="token keyword">break</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
            <span class="token comment">// 这里是两个链表都不为空的时候，就比较下大小</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>l1<span class="token punctuation">.</span>val <span class="token operator">&lt;</span> l2<span class="token punctuation">.</span>val<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                current<span class="token punctuation">.</span>val <span class="token operator">=</span> l1<span class="token punctuation">.</span>val<span class="token punctuation">;</span>
                l1 <span class="token operator">=</span> l1<span class="token punctuation">.</span>next<span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                current<span class="token punctuation">.</span>val <span class="token operator">=</span> l2<span class="token punctuation">.</span>val<span class="token punctuation">;</span>
                l2 <span class="token operator">=</span> l2<span class="token punctuation">.</span>next<span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
            <span class="token comment">// 这里是new个新的，其实也可以放在循环头上</span>
            current<span class="token punctuation">.</span>next <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ListNode</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            current <span class="token operator">=</span> current<span class="token punctuation">.</span>next<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        current <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
        <span class="token comment">// 返回这个头结点</span>
        <span class="token keyword">return</span> merged<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="结果"><a href="#结果" class="headerlink" title="结果"></a>结果</h3><p><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/4iHpzc.png"></p>
]]></content>
      <categories>
        <category>Java</category>
        <category>leetcode</category>
      </categories>
      <tags>
        <tag>leetcode</tag>
        <tag>java</tag>
        <tag>题解</tag>
      </tags>
  </entry>
  <entry>
    <title>Leetcode 028 实现 strStr() ( Implement strStr() ) 题解分析</title>
    <url>/2021/10/31/Leetcode-028-%E5%AE%9E%E7%8E%B0-strStr-Implement-strStr-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/</url>
    <content><![CDATA[<h3 id="题目介绍"><a href="#题目介绍" class="headerlink" title="题目介绍"></a>题目介绍</h3><p>Implement <code>strStr()</code>.</p>
<p>Return the index of the first occurrence of needle in haystack, or <code>-1</code> if <code>needle</code> is not part of <code>haystack</code>.</p>
<h4 id="Clarification"><a href="#Clarification" class="headerlink" title="Clarification:"></a>Clarification:</h4><p>What should we return when <code>needle</code> is an empty string? This is a great question to ask during an interview.</p>
<p>For the purpose of this problem, we will return 0 when <code>needle</code> is an empty string. This is consistent to C’s <code>strstr()</code> and Java’s <code>indexOf()</code>.</p>
<h3 id="示例"><a href="#示例" class="headerlink" title="示例"></a>示例</h3><p>Example 1:</p>
<pre class="line-numbers language-none"><code class="language-none">Input: haystack &#x3D; &quot;hello&quot;, needle &#x3D; &quot;ll&quot;
Output: 2<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>Example 2:</p>
<pre class="line-numbers language-none"><code class="language-none">Input: haystack &#x3D; &quot;aaaaa&quot;, needle &#x3D; &quot;bba&quot;
Output: -1<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>Example 3:</p>
<pre class="line-numbers language-none"><code class="language-none">Input: haystack &#x3D; &quot;&quot;, needle &#x3D; &quot;&quot;
Output: 0<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<h3 id="题解"><a href="#题解" class="headerlink" title="题解"></a>题解</h3><p>字符串比较其实是写代码里永恒的主题，底层的编译器等处理肯定需要字符串对比，像 kmp 算法也是很厉害</p>
<h4 id="code"><a href="#code" class="headerlink" title="code"></a>code</h4><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">strStr</span><span class="token punctuation">(</span><span class="token class-name">String</span> haystack<span class="token punctuation">,</span> <span class="token class-name">String</span> needle<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">// 如果两个字符串都为空，返回 -1</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>haystack <span class="token operator">==</span> <span class="token keyword">null</span> <span class="token operator">||</span> needle <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token comment">// 如果 haystack 长度小于 needle 长度，返回 -1</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>haystack<span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&lt;</span> needle<span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token comment">// 如果 needle 为空字符串，返回 0</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>needle<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span><span class="token string">""</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token comment">// 如果两者相等，返回 0</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>haystack<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>needle<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">int</span> needleLength <span class="token operator">=</span> needle<span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">int</span> haystackLength <span class="token operator">=</span> haystack<span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> needleLength <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">;</span> i <span class="token operator">&lt;=</span> haystackLength <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token comment">// 比较 needle 最后一个字符，倒着比较稍微节省点时间</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>needle<span class="token punctuation">.</span><span class="token function">charAt</span><span class="token punctuation">(</span>needleLength <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token operator">==</span> haystack<span class="token punctuation">.</span><span class="token function">charAt</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token comment">// 如果needle 是 1 的话直接可以返回 i 作为位置了</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>needle<span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">return</span> i<span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
                <span class="token keyword">boolean</span> flag <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
                <span class="token comment">// 原来比的是 needle 的最后一个位置，然后这边从倒数第二个位置开始</span>
                <span class="token keyword">int</span> j <span class="token operator">=</span> needle<span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-</span> <span class="token number">2</span><span class="token punctuation">;</span>
                <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token punctuation">;</span> j <span class="token operator">>=</span> <span class="token number">0</span><span class="token punctuation">;</span> j<span class="token operator">--</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token comment">// 这里的 i- (needleLength - j) + 1 ) 比较绕，其实是外循环的 i 表示当前 i 位置的字符跟 needle 最后一个字符</span>
                    <span class="token comment">// 相同，j 在上面的循环中--，对应的 haystack 也要在 i 这个位置 -- ，对应的位置就是 i - (needleLength - j) + 1</span>
                    <span class="token keyword">if</span> <span class="token punctuation">(</span>needle<span class="token punctuation">.</span><span class="token function">charAt</span><span class="token punctuation">(</span>j<span class="token punctuation">)</span> <span class="token operator">!=</span> haystack<span class="token punctuation">.</span><span class="token function">charAt</span><span class="token punctuation">(</span>i <span class="token operator">-</span> <span class="token punctuation">(</span>needleLength <span class="token operator">-</span> j<span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        flag <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
                        <span class="token keyword">break</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span>
                <span class="token comment">// 循环完了之后，如果 flag 为 true 说明 从 i 开始倒着对比都相同，但是这里需要起始位置，就需要</span>
                <span class="token comment">// i - needleLength + 1</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>flag<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">return</span> i <span class="token operator">-</span> needleLength <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token comment">// 这里表示未找到</span>
        <span class="token keyword">return</span>  <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>]]></content>
      <categories>
        <category>Java</category>
        <category>leetcode</category>
      </categories>
      <tags>
        <tag>leetcode</tag>
        <tag>java</tag>
        <tag>题解</tag>
      </tags>
  </entry>
  <entry>
    <title>Leetcode 053 最大子序和 ( Maximum Subarray ) 题解分析</title>
    <url>/2021/11/28/Leetcode-053-%E6%9C%80%E5%A4%A7%E5%AD%90%E5%BA%8F%E5%92%8C-Maximum-Subarray-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/</url>
    <content><![CDATA[<h3 id="题目介绍"><a href="#题目介绍" class="headerlink" title="题目介绍"></a>题目介绍</h3><p>Given an integer array <code>nums</code>, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.</p>
<p>A <strong>subarray</strong> is a <strong>contiguous</strong> part of an array.</p>
<h4 id="示例"><a href="#示例" class="headerlink" title="示例"></a>示例</h4><p><strong>Example 1:</strong></p>
<blockquote>
<p>Input: nums = [-2,1,-3,4,-1,2,1,-5,4]<br>Output: 6<br>Explanation: [4,-1,2,1] has the largest sum = 6.  </p>
</blockquote>
<p><strong>Example 2:</strong></p>
<blockquote>
<p>Input: nums = [1]<br>Output: 1  </p>
</blockquote>
<p><strong>Example 3:</strong></p>
<blockquote>
<p>Input: nums = [5,4,-1,7,8]<br>Output: 23</p>
</blockquote>
<p>说起来这个题其实非常有渊源，大学数据结构的第一个题就是这个，而最佳的算法就是传说中的 online 算法，就是遍历一次就完了，最基本的做法就是记下来所有的连续子数组，然后求出最大的那个。</p>
<h3 id="代码"><a href="#代码" class="headerlink" title="代码"></a>代码</h3><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">maxSubArray</span><span class="token punctuation">(</span><span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> nums<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">int</span> max <span class="token operator">=</span> nums<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
        <span class="token keyword">int</span> sum <span class="token operator">=</span> nums<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> nums<span class="token punctuation">.</span>length<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token comment">// 这里最重要的就是这一行了，其实就是如果前面的 sum 是小于 0 的，那么就不需要前面的 sum，反正加上了还不如不加大</span>
            sum <span class="token operator">=</span> <span class="token class-name">Math</span><span class="token punctuation">.</span><span class="token function">max</span><span class="token punctuation">(</span>nums<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">,</span> sum <span class="token operator">+</span> nums<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token comment">// max 是用来承载最大值的</span>
            max <span class="token operator">=</span> <span class="token class-name">Math</span><span class="token punctuation">.</span><span class="token function">max</span><span class="token punctuation">(</span>max<span class="token punctuation">,</span> sum<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">return</span> max<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>]]></content>
      <categories>
        <category>Java</category>
        <category>leetcode</category>
      </categories>
      <tags>
        <tag>leetcode</tag>
        <tag>java</tag>
        <tag>题解</tag>
      </tags>
  </entry>
  <entry>
    <title>Leetcode 104 二叉树的最大深度(Maximum Depth of Binary Tree) 题解分析</title>
    <url>/2020/10/25/Leetcode-104-%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E5%A4%A7%E6%B7%B1%E5%BA%A6-Maximum-Depth-of-Binary-Tree-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/</url>
    <content><![CDATA[<h2 id="题目介绍"><a href="#题目介绍" class="headerlink" title="题目介绍"></a>题目介绍</h2><p>给定一个二叉树，找出其最大深度。</p>
<p>二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。</p>
<p>说明: 叶子节点是指没有子节点的节点。</p>
<p>示例：<br>给定二叉树 [3,9,20,null,null,15,7]，</p>
<pre class="line-numbers language-none"><code class="language-none">  3
 &#x2F; \
9  20
  &#x2F;  \
 15   7<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>返回它的最大深度 3 。</p>
<h2 id="代码"><a href="#代码" class="headerlink" title="代码"></a>代码</h2><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">// 主体是个递归的应用</span>
<span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">maxDepth</span><span class="token punctuation">(</span><span class="token class-name">TreeNode</span> root<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token comment">// 节点的退出条件之一</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>root <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">int</span> left <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
    <span class="token keyword">int</span> right <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
    <span class="token comment">// 存在左子树，就递归左子树</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>root<span class="token punctuation">.</span>left <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        left <span class="token operator">=</span> <span class="token function">maxDepth</span><span class="token punctuation">(</span>root<span class="token punctuation">.</span>left<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token comment">// 存在右子树，就递归右子树</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>root<span class="token punctuation">.</span>right <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        right <span class="token operator">=</span> <span class="token function">maxDepth</span><span class="token punctuation">(</span>root<span class="token punctuation">.</span>right<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token comment">// 前面返回后，左右取大者</span>
    <span class="token keyword">return</span> <span class="token class-name">Math</span><span class="token punctuation">.</span><span class="token function">max</span><span class="token punctuation">(</span>left <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">,</span> right <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="分析"><a href="#分析" class="headerlink" title="分析"></a>分析</h2><p>其实对于树这类题，一般是以递归形式比较方便，只是要注意退出条件</p>
]]></content>
      <categories>
        <category>Java</category>
        <category>leetcode</category>
        <category>Binary Tree</category>
        <category>java</category>
        <category>Binary Tree</category>
        <category>DFS</category>
      </categories>
      <tags>
        <tag>leetcode</tag>
        <tag>java</tag>
        <tag>Binary Tree</tag>
        <tag>DFS</tag>
        <tag>二叉树</tag>
        <tag>题解</tag>
      </tags>
  </entry>
  <entry>
    <title>Leetcode 105 从前序与中序遍历序列构造二叉树(Construct Binary Tree from Preorder and Inorder Traversal) 题解分析</title>
    <url>/2020/12/13/Leetcode-105-%E4%BB%8E%E5%89%8D%E5%BA%8F%E4%B8%8E%E4%B8%AD%E5%BA%8F%E9%81%8D%E5%8E%86%E5%BA%8F%E5%88%97%E6%9E%84%E9%80%A0%E4%BA%8C%E5%8F%89%E6%A0%91-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/</url>
    <content><![CDATA[<h2 id="题目介绍"><a href="#题目介绍" class="headerlink" title="题目介绍"></a>题目介绍</h2><p>Given preorder and inorder traversal of a tree, construct the binary tree.<br>给定一棵树的前序和中序遍历，构造出一棵二叉树</p>
<h3 id="注意"><a href="#注意" class="headerlink" title="注意"></a>注意</h3><p>You may assume that duplicates do not exist in the tree.<br>你可以假设树中没有重复的元素。(PS: 不然就没法做了呀)</p>
<h3 id="例子"><a href="#例子" class="headerlink" title="例子:"></a>例子:</h3><pre class="line-numbers language-none"><code class="language-none">preorder &#x3D; [3,9,20,15,7]
inorder &#x3D; [9,3,15,20,7]<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>返回的二叉树</p>
<pre class="line-numbers language-none"><code class="language-none">  3
 &#x2F; \
9  20
  &#x2F;  \
 15   7<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<h2 id="简要分析"><a href="#简要分析" class="headerlink" title="简要分析"></a>简要分析</h2><p>看到这个题可以想到一个比较常规的解法就是递归拆树，前序就是根左右，中序就是左根右，然后就是通过前序已经确定的根在中序中找到，然后去划分左右子树，这个例子里是 3，找到中序中的位置，那么就可以确定，9 是左子树，15,20,7是右子树，然后对应的可以根据左右子树的元素数量在前序中划分左右子树，再继续递归就行</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">class</span> <span class="token class-name">Solution</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">public</span> <span class="token class-name">TreeNode</span> <span class="token function">buildTree</span><span class="token punctuation">(</span><span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> preorder<span class="token punctuation">,</span> <span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> inorder<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
      <span class="token comment">// 获取下数组长度</span>
        <span class="token keyword">int</span> n <span class="token operator">=</span> preorder<span class="token punctuation">.</span>length<span class="token punctuation">;</span>
        <span class="token comment">// 排除一下异常和边界</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>n <span class="token operator">!=</span> inorder<span class="token punctuation">.</span>length<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>n <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>n <span class="token operator">==</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">TreeNode</span><span class="token punctuation">(</span>preorder<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token comment">// 获得根节点</span>
        <span class="token class-name">TreeNode</span> node <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">TreeNode</span><span class="token punctuation">(</span>preorder<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">int</span> pos <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
        <span class="token comment">// 找到中序中的位置</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> inorder<span class="token punctuation">.</span>length<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>node<span class="token punctuation">.</span>val <span class="token operator">==</span> inorder<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                pos <span class="token operator">=</span> i<span class="token punctuation">;</span>
                <span class="token keyword">break</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token comment">// 划分左右再进行递归，注意下`Arrays.copyOfRange`的用法</span>
        node<span class="token punctuation">.</span>left <span class="token operator">=</span> <span class="token function">buildTree</span><span class="token punctuation">(</span><span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">copyOfRange</span><span class="token punctuation">(</span>preorder<span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">,</span> pos <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">copyOfRange</span><span class="token punctuation">(</span>inorder<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> pos<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        node<span class="token punctuation">.</span>right <span class="token operator">=</span> <span class="token function">buildTree</span><span class="token punctuation">(</span><span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">copyOfRange</span><span class="token punctuation">(</span>preorder<span class="token punctuation">,</span> pos <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">,</span> n<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">copyOfRange</span><span class="token punctuation">(</span>inorder<span class="token punctuation">,</span> pos <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">,</span> n<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> node<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>]]></content>
      <categories>
        <category>Java</category>
        <category>leetcode</category>
        <category>Binary Tree</category>
        <category>java</category>
        <category>Binary Tree</category>
        <category>DFS</category>
      </categories>
      <tags>
        <tag>leetcode</tag>
        <tag>java</tag>
        <tag>Binary Tree</tag>
        <tag>二叉树</tag>
        <tag>题解</tag>
        <tag>递归</tag>
        <tag>Preorder Traversal</tag>
        <tag>Inorder Traversal</tag>
        <tag>前序</tag>
        <tag>中序</tag>
      </tags>
  </entry>
  <entry>
    <title>Leetcode 121 买卖股票的最佳时机(Best Time to Buy and Sell Stock) 题解分析</title>
    <url>/2021/03/14/Leetcode-121-%E4%B9%B0%E5%8D%96%E8%82%A1%E7%A5%A8%E7%9A%84%E6%9C%80%E4%BD%B3%E6%97%B6%E6%9C%BA-Best-Time-to-Buy-and-Sell-Stock-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/</url>
    <content><![CDATA[<h3 id="题目介绍"><a href="#题目介绍" class="headerlink" title="题目介绍"></a>题目介绍</h3><p>You are given an array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the i<sup>th</sup> day.</p>
<p>You want to maximize your profit by choosing a <strong>single day</strong> to buy one stock and choosing a <strong>different day in the future</strong> to sell that stock.</p>
<p>Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return <code>0</code>.</p>
<p>给定一个数组 <code>prices</code> ，它的第 <code>i</code> 个元素 <code>prices[i]</code> 表示一支给定股票第 <code>i</code> 天的价格。</p>
<p>你只能选择 <strong>某一天</strong> 买入这只股票，并选择在 <strong>未来的某一个不同的日子</strong> 卖出该股票。设计一个算法来计算你所能获取的最大利润。</p>
<p>返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润，返回 <code>0</code> 。</p>
<h3 id="简单分析"><a href="#简单分析" class="headerlink" title="简单分析"></a>简单分析</h3><p>其实这个跟二叉树的最长路径和有点类似，需要找到整体的最大收益，但是在迭代过程中需要一个当前的值</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">int</span> maxSofar <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">maxProfit</span><span class="token punctuation">(</span><span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> prices<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>prices<span class="token punctuation">.</span>length <span class="token operator">&lt;=</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">int</span> maxIn <span class="token operator">=</span> prices<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
    <span class="token keyword">int</span> maxOut <span class="token operator">=</span> prices<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> prices<span class="token punctuation">.</span>length<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>maxIn <span class="token operator">></span> prices<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token comment">// 当循环当前值小于之前的买入值时就当成买入值，同时卖出也要更新</span>
            maxIn <span class="token operator">=</span> prices<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">;</span>
            maxOut <span class="token operator">=</span> prices<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>prices<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">></span> maxOut<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token comment">// 表示一个可卖出点，即比买入值高时</span>
            maxOut <span class="token operator">=</span> prices<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">;</span>
            <span class="token comment">// 需要设置一个历史值</span>
            maxSofar <span class="token operator">=</span> <span class="token class-name">Math</span><span class="token punctuation">.</span><span class="token function">max</span><span class="token punctuation">(</span>maxSofar<span class="token punctuation">,</span> maxOut <span class="token operator">-</span> maxIn<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">return</span> maxSofar<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="总结下"><a href="#总结下" class="headerlink" title="总结下"></a>总结下</h3><p>一开始看到 easy 就觉得是很简单，就没有 maxSofar ，但是一提交就出现问题了<br>对于<code>[2, 4, 1]</code>这种就会变成 0，所以还是需要一个历史值来存放历史最大值，这题有点动态规划的意思</p>
]]></content>
      <categories>
        <category>Java</category>
        <category>leetcode</category>
        <category>java</category>
        <category>DP</category>
        <category>DP</category>
      </categories>
      <tags>
        <tag>leetcode</tag>
        <tag>java</tag>
        <tag>题解</tag>
        <tag>DP</tag>
      </tags>
  </entry>
  <entry>
    <title>Leetcode 124 二叉树中的最大路径和(Binary Tree Maximum Path Sum) 题解分析</title>
    <url>/2021/01/24/Leetcode-124-%E4%BA%8C%E5%8F%89%E6%A0%91%E4%B8%AD%E7%9A%84%E6%9C%80%E5%A4%A7%E8%B7%AF%E5%BE%84%E5%92%8C-Binary-Tree-Maximum-Path-Sum-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/</url>
    <content><![CDATA[<h3 id="题目介绍"><a href="#题目介绍" class="headerlink" title="题目介绍"></a>题目介绍</h3><p>A <strong>path</strong> in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence <strong>at most once</strong>. Note that the path does not need to pass through the root.</p>
<p>The <strong>path sum</strong> of a path is the sum of the node’s values in the path.</p>
<p>Given the <code>root</code> of a binary tree, return the maximum <strong>path sum</strong> of any path.</p>
<p><strong>路径</strong> 被定义为一条从树中任意节点出发，沿父节点-子节点连接，达到任意节点的序列。该路径 <strong>至少包含一个</strong> 节点，且不一定经过根节点。</p>
<p><strong>路径和</strong> 是路径中各节点值的总和。</p>
<p>给你一个二叉树的根节点 <code>root</code> ，返回其 <strong>最大路径和</strong></p>
<h3 id="简要分析"><a href="#简要分析" class="headerlink" title="简要分析"></a>简要分析</h3><p>其实这个题目会被误解成比较简单，左子树最大的，或者右子树最大的，或者两边加一下，仔细想想都不对，其实有可能是产生于左子树中，或者右子树中，这两个都是指跟左子树根还有右子树根没关系的，这么说感觉不太容易理解，画个图<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/SfxIEy.png"><br>可以看到图里，其实最长路径和是左边这个子树组成的，跟根节点还有右子树完全没关系，然后再想一种情况，如果是整棵树就是图中的左子树，那么这个最长路径和就是左子树加右子树加根节点了，所以不是我一开始想得那么简单，在代码实现中也需要一些技巧</p>
<h3 id="代码"><a href="#代码" class="headerlink" title="代码"></a>代码</h3><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">int</span> ansNew <span class="token operator">=</span> <span class="token class-name">Integer</span><span class="token punctuation">.</span>MIN_VALUE<span class="token punctuation">;</span>
<span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">maxPathSum</span><span class="token punctuation">(</span><span class="token class-name">TreeNode</span> root<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token function">maxSumNew</span><span class="token punctuation">(</span>root<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> ansNew<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    
<span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">maxSumNew</span><span class="token punctuation">(</span><span class="token class-name">TreeNode</span> root<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>root <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token comment">// 这里是个简单的递归，就是去递归左右子树，但是这里其实有个概念，当这样处理时，其实相当于把子树的内部的最大路径和已经算出来了</span>
    <span class="token keyword">int</span> left <span class="token operator">=</span> <span class="token function">maxSumNew</span><span class="token punctuation">(</span>root<span class="token punctuation">.</span>left<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">int</span> right <span class="token operator">=</span> <span class="token function">maxSumNew</span><span class="token punctuation">(</span>root<span class="token punctuation">.</span>right<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">// 这里前面我有点没想明白，但是看到 ansNew 的比较，其实相当于，返回的是三种情况里的最大值，一个是左子树+根，一个是右子树+根，一个是单独根节点，</span>
    <span class="token comment">// 这样这个递归的返回才会有意义，不然像原来的方法，它可能是跳着的，但是这种情况其实是借助于 ansNew 这个全局的最大值，因为原来我觉得要比较的是</span>
    <span class="token comment">// left, right, left + root , right + root, root, left + right + root 这些的最大值，这里是分成了两个阶段，left 跟 right 的最大值已经在上面的</span>
    <span class="token comment">// 调用过程中赋值给 ansNew 了    </span>
    <span class="token keyword">int</span> currentSum <span class="token operator">=</span> <span class="token class-name">Math</span><span class="token punctuation">.</span><span class="token function">max</span><span class="token punctuation">(</span><span class="token class-name">Math</span><span class="token punctuation">.</span><span class="token function">max</span><span class="token punctuation">(</span>root<span class="token punctuation">.</span>val <span class="token operator">+</span> left <span class="token punctuation">,</span> root<span class="token punctuation">.</span>val <span class="token operator">+</span> right<span class="token punctuation">)</span><span class="token punctuation">,</span> root<span class="token punctuation">.</span>val<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">// 这边返回的是 currentSum，然后再用它跟 left + right + root 进行对比，然后再去更新 ans</span>
    <span class="token comment">// PS: 有个小点也是这边的破局点，就是这个 ansNew</span>
    <span class="token keyword">int</span> res <span class="token operator">=</span> <span class="token class-name">Math</span><span class="token punctuation">.</span><span class="token function">max</span><span class="token punctuation">(</span>left <span class="token operator">+</span> right <span class="token operator">+</span> root<span class="token punctuation">.</span>val<span class="token punctuation">,</span> currentSum<span class="token punctuation">)</span><span class="token punctuation">;</span>
    ans <span class="token operator">=</span> <span class="token class-name">Math</span><span class="token punctuation">.</span><span class="token function">max</span><span class="token punctuation">(</span>res<span class="token punctuation">,</span> ans<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> currentSum<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>这里非常重要的就是 ansNew 是最后的一个结果，而对于 maxSumNew 这个函数的返回值其实是需要包含了一个连续结果，因为要返回继续去算路径和，所以返回的是 currentSum，最终结果是 ansNew</p>
<h3 id="结果图"><a href="#结果图" class="headerlink" title="结果图"></a>结果图</h3><p>难得有个 100%，贴个图哈哈<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/iipgv0.png"></p>
]]></content>
      <categories>
        <category>Java</category>
        <category>leetcode</category>
        <category>Binary Tree</category>
        <category>java</category>
        <category>Binary Tree</category>
      </categories>
      <tags>
        <tag>leetcode</tag>
        <tag>java</tag>
        <tag>Binary Tree</tag>
        <tag>二叉树</tag>
        <tag>题解</tag>
      </tags>
  </entry>
  <entry>
    <title>Leetcode 155 最小栈(Min Stack) 题解分析</title>
    <url>/2020/12/06/Leetcode-155-%E6%9C%80%E5%B0%8F%E6%A0%88-Min-Stack-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/</url>
    <content><![CDATA[<h2 id="题目介绍"><a href="#题目介绍" class="headerlink" title="题目介绍"></a>题目介绍</h2><p>Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.<br>设计一个栈，支持压栈，出站，获取栈顶元素，通过常数级复杂度获取栈中的最小元素</p>
<ul>
<li>push(x) – Push element x onto stack.</li>
<li>pop() – Removes the element on top of the stack.</li>
<li>top() – Get the top element.</li>
<li>getMin() – Retrieve the minimum element in the stack.</li>
</ul>
<h2 id="示例"><a href="#示例" class="headerlink" title="示例"></a>示例</h2><p>Example 1:</p>
<pre class="line-numbers language-none"><code class="language-none">Input
[&quot;MinStack&quot;,&quot;push&quot;,&quot;push&quot;,&quot;push&quot;,&quot;getMin&quot;,&quot;pop&quot;,&quot;top&quot;,&quot;getMin&quot;]
[[],[-2],[0],[-3],[],[],[],[]]

Output
[null,null,null,null,-3,null,0,-2]

Explanation
MinStack minStack &#x3D; new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); &#x2F;&#x2F; return -3
minStack.pop();
minStack.top();    &#x2F;&#x2F; return 0
minStack.getMin(); &#x2F;&#x2F; return -2<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="简要分析"><a href="#简要分析" class="headerlink" title="简要分析"></a>简要分析</h2><p>其实现在大部分语言都自带类栈的数据结构，Java 也自带 stack 这个数据结构，所以这个题的主要难点的就是常数级的获取最小元素，最开始的想法是就一个栈外加一个记录最小值的变量就行了，但是仔细一想是不行的，因为随着元素被 pop 出去，这个最小值也可能需要梗着变化，就不太好判断了，所以后面是用了一个辅助栈。</p>
<h2 id="代码"><a href="#代码" class="headerlink" title="代码"></a>代码</h2><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">class</span> <span class="token class-name">MinStack</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">// 这个作为主栈</span>
        <span class="token class-name">Stack</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">></span></span> s1 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Stack</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">// 这个作为辅助栈，放最小值的栈</span>
        <span class="token class-name">Stack</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">></span></span> s2 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Stack</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">/** initialize your data structure here. */</span>
        <span class="token keyword">public</span> <span class="token class-name">MinStack</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>

        <span class="token punctuation">&#125;</span>

        <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">push</span><span class="token punctuation">(</span><span class="token keyword">int</span> x<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token comment">// 放入主栈</span>
            s1<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span>x<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token comment">// 当 s2 是空或者当前值是小于"等于" s2 栈顶时，压入辅助最小值的栈</span>
            <span class="token comment">// 注意这里的"等于"非常必要，因为当最小值有多个的情况下，也需要压入栈，否则在 pop 的时候就会不对等</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>s2<span class="token punctuation">.</span><span class="token function">isEmpty</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">||</span> x <span class="token operator">&lt;=</span> s2<span class="token punctuation">.</span><span class="token function">peek</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                s2<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span>x<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">pop</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token comment">// 首先就是主栈要 pop，然后就是第二个了，跟上面的"等于"很有关系，</span>
            <span class="token comment">// 因为如果有两个最小值，如果前面等于的情况没有压栈，那这边相等的时候 pop 就会少一个了，可能就导致最小值不对了</span>
            <span class="token keyword">int</span> x <span class="token operator">=</span> s1<span class="token punctuation">.</span><span class="token function">pop</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>x <span class="token operator">==</span> s2<span class="token punctuation">.</span><span class="token function">peek</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>  <span class="token punctuation">&#123;</span>
                s2<span class="token punctuation">.</span><span class="token function">pop</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">top</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token comment">// 栈顶的元素</span>
            <span class="token keyword">return</span> s1<span class="token punctuation">.</span><span class="token function">peek</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">getMin</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token comment">// 辅助最小栈的栈顶</span>
            <span class="token keyword">return</span> s2<span class="token punctuation">.</span><span class="token function">peek</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

]]></content>
      <categories>
        <category>Java</category>
        <category>leetcode</category>
        <category>java</category>
        <category>stack</category>
        <category>stack</category>
      </categories>
      <tags>
        <tag>leetcode</tag>
        <tag>java</tag>
        <tag>题解</tag>
        <tag>stack</tag>
        <tag>min stack</tag>
        <tag>最小栈</tag>
        <tag>leetcode 155</tag>
      </tags>
  </entry>
  <entry>
    <title>Leetcode 160 相交链表(intersection-of-two-linked-lists) 题解分析</title>
    <url>/2021/01/10/Leetcode-160-%E7%9B%B8%E4%BA%A4%E9%93%BE%E8%A1%A8-intersection-of-two-linked-lists-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/</url>
    <content><![CDATA[<h2 id="题目介绍"><a href="#题目介绍" class="headerlink" title="题目介绍"></a>题目介绍</h2><p>写一个程序找出两个单向链表的交叉起始点，可能是我英语不好，图里画的其实还有一点是交叉以后所有节点都是相同的<br>Write a program to find the node at which the intersection of two singly linked lists begins.</p>
<p>For example, the following two linked lists:<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/nkha2z.png"><br>begin to intersect at node c1.</p>
<h3 id="Example-1"><a href="#Example-1" class="headerlink" title="Example 1:"></a>Example 1:</h3><p><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/1TrhYe.png"></p>
<pre class="line-numbers language-none"><code class="language-none">Input: intersectVal &#x3D; 8, listA &#x3D; [4,1,8,4,5], listB &#x3D; [5,6,1,8,4,5], skipA &#x3D; 2, skipB &#x3D; 3
Output: Reference of the node with value &#x3D; 8
Input Explanation: The intersected node&#39;s value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<h2 id="分析题解"><a href="#分析题解" class="headerlink" title="分析题解"></a>分析题解</h2><p>一开始没什么头绪，感觉只能最原始的遍历，后来看了一些文章，发现比较简单的方式就是先找两个链表的长度差，因为从相交点开始肯定是长度一致的，这是个很好的解题突破口，找到长度差以后就是先跳过长链表的较长部分，然后开始同步遍历比较 A，B 链表；</p>
<h3 id="代码"><a href="#代码" class="headerlink" title="代码"></a>代码</h3><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">ListNode</span> <span class="token function">getIntersectionNode</span><span class="token punctuation">(</span><span class="token class-name">ListNode</span> headA<span class="token punctuation">,</span> <span class="token class-name">ListNode</span> headB<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>headA <span class="token operator">==</span> <span class="token keyword">null</span> <span class="token operator">||</span> headB <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token comment">// 算 A 的长度</span>
        <span class="token keyword">int</span> countA <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
        <span class="token class-name">ListNode</span> tailA <span class="token operator">=</span> headA<span class="token punctuation">;</span>
        <span class="token keyword">while</span> <span class="token punctuation">(</span>tailA <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            tailA <span class="token operator">=</span> tailA<span class="token punctuation">.</span>next<span class="token punctuation">;</span>
            countA<span class="token operator">++</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token comment">// 算 B 的长度</span>
        <span class="token keyword">int</span> countB <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
        <span class="token class-name">ListNode</span> tailB <span class="token operator">=</span> headB<span class="token punctuation">;</span>
        <span class="token keyword">while</span> <span class="token punctuation">(</span>tailB <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            tailB <span class="token operator">=</span> tailB<span class="token punctuation">.</span>next<span class="token punctuation">;</span>
            countB<span class="token operator">++</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        tailA <span class="token operator">=</span> headA<span class="token punctuation">;</span>
        tailB <span class="token operator">=</span> headB<span class="token punctuation">;</span>
        <span class="token comment">// 依据长度差，先让长的链表 tail 指针往后移</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>countA <span class="token operator">></span> countB<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">while</span> <span class="token punctuation">(</span>countA <span class="token operator">></span> countB<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                tailA <span class="token operator">=</span> tailA<span class="token punctuation">.</span>next<span class="token punctuation">;</span>
                countA<span class="token operator">--</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>countA <span class="token operator">&lt;</span> countB<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">while</span> <span class="token punctuation">(</span>countA <span class="token operator">&lt;</span> countB<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                tailB <span class="token operator">=</span> tailB<span class="token punctuation">.</span>next<span class="token punctuation">;</span>
                countB<span class="token operator">--</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token comment">// 然后以相同速度遍历两个链表比较</span>
        <span class="token keyword">while</span> <span class="token punctuation">(</span>tailA <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>tailA <span class="token operator">==</span> tailB<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">return</span> tailA<span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                tailA <span class="token operator">=</span> tailA<span class="token punctuation">.</span>next<span class="token punctuation">;</span>
                tailB <span class="token operator">=</span> tailB<span class="token punctuation">.</span>next<span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">return</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>可能缺少这种思维，做的还是比较少，所以没法一下子反应过来，需要锻炼，我的第一反应是两重遍历，不过那样复杂度就高了，这里应该是只有 O(N) 的复杂度。</p>
]]></content>
      <categories>
        <category>Java</category>
        <category>leetcode</category>
        <category>Linked List</category>
        <category>java</category>
        <category>Linked List</category>
      </categories>
      <tags>
        <tag>leetcode</tag>
        <tag>java</tag>
        <tag>题解</tag>
        <tag>Linked List</tag>
      </tags>
  </entry>
  <entry>
    <title>Leetcode 2 Add Two Numbers 题解分析</title>
    <url>/2020/10/11/Leetcode-2-Add-Two-Numbers-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/</url>
    <content><![CDATA[<p>又 roll 到了一个以前做过的题，不过现在用 Java 也来写一下，是 easy 级别的，所以就简单说下</p>
<h2 id="简要介绍"><a href="#简要介绍" class="headerlink" title="简要介绍"></a>简要介绍</h2><p>You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.</p>
<p>You may assume the two numbers do not contain any leading zero, except the number 0 itself.<br>就是给了两个链表，用来表示两个非负的整数，在链表中倒序放着，每个节点包含一位的数字，把他们加起来以后也按照原来的链表结构输出</p>
<h2 id="样例"><a href="#样例" class="headerlink" title="样例"></a>样例</h2><h4 id="example-1"><a href="#example-1" class="headerlink" title="example 1"></a>example 1</h4><pre class="line-numbers language-none"><code class="language-none">Input: l1 &#x3D; [2,4,3], l2 &#x3D; [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 &#x3D; 807.<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<h4 id="example-2"><a href="#example-2" class="headerlink" title="example 2"></a>example 2</h4><pre class="line-numbers language-none"><code class="language-none">Input: l1 &#x3D; [0], l2 &#x3D; [0]
Output: [0]<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<h4 id="example-3"><a href="#example-3" class="headerlink" title="example 3"></a>example 3</h4><pre class="line-numbers language-none"><code class="language-none">Input: l1 &#x3D; [9,9,9,9,9,9,9], l2 &#x3D; [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<h2 id="题解"><a href="#题解" class="headerlink" title="题解"></a>题解</h2><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">ListNode</span> <span class="token function">addTwoNumbers</span><span class="token punctuation">(</span><span class="token class-name">ListNode</span> l1<span class="token punctuation">,</span> <span class="token class-name">ListNode</span> l2<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">ListNode</span> root <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ListNode</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>l1 <span class="token operator">==</span> <span class="token keyword">null</span> <span class="token operator">&amp;&amp;</span> l2 <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> root<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token class-name">ListNode</span> tail <span class="token operator">=</span> root<span class="token punctuation">;</span>
        <span class="token keyword">int</span> entered <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
        <span class="token comment">// 这个条件加了 entered，就是还有进位的数</span>
        <span class="token keyword">while</span> <span class="token punctuation">(</span>l1 <span class="token operator">!=</span> <span class="token keyword">null</span> <span class="token operator">||</span> l2 <span class="token operator">!=</span> <span class="token keyword">null</span> <span class="token operator">||</span> entered <span class="token operator">!=</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">int</span> temp <span class="token operator">=</span> entered<span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>l1 <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                temp <span class="token operator">+=</span> l1<span class="token punctuation">.</span>val<span class="token punctuation">;</span>
                l1 <span class="token operator">=</span> l1<span class="token punctuation">.</span>next<span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>l2 <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                temp <span class="token operator">+=</span> l2<span class="token punctuation">.</span>val<span class="token punctuation">;</span>
                l2 <span class="token operator">=</span> l2<span class="token punctuation">.</span>next<span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
            entered <span class="token operator">=</span> <span class="token punctuation">(</span>temp <span class="token operator">-</span> temp <span class="token operator">%</span> <span class="token number">10</span><span class="token punctuation">)</span> <span class="token operator">/</span> <span class="token number">10</span><span class="token punctuation">;</span>
            tail<span class="token punctuation">.</span>val <span class="token operator">=</span> temp <span class="token operator">%</span> <span class="token number">10</span><span class="token punctuation">;</span>
            <span class="token comment">// 循环内部的控制是为了排除最后的空节点</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>l1 <span class="token operator">!=</span> <span class="token keyword">null</span> <span class="token operator">||</span> l2 <span class="token operator">!=</span> <span class="token keyword">null</span> <span class="token operator">||</span> entered <span class="token operator">!=</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                tail<span class="token punctuation">.</span>next <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ListNode</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                tail <span class="token operator">=</span> tail<span class="token punctuation">.</span>next<span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
<span class="token comment">//        tail = null;</span>
        <span class="token keyword">return</span> root<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这里唯二需要注意的就是两个点，一个是循环条件需要包含进位值还存在的情况，还有一个是最后一个节点，如果是空的了，就不要在 new 一个出来了，写的比较挫</p>
]]></content>
      <categories>
        <category>Java</category>
        <category>leetcode</category>
        <category>java</category>
        <category>linked list</category>
        <category>linked list</category>
      </categories>
      <tags>
        <tag>leetcode</tag>
        <tag>java</tag>
        <tag>题解</tag>
        <tag>linked list</tag>
      </tags>
  </entry>
  <entry>
    <title>Leetcode 234 回文链表(Palindrome Linked List) 题解分析</title>
    <url>/2020/11/15/Leetcode-234-%E5%9B%9E%E6%96%87%E8%81%94%E8%A1%A8-Palindrome-Linked-List-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/</url>
    <content><![CDATA[<h2 id="题目介绍"><a href="#题目介绍" class="headerlink" title="题目介绍"></a>题目介绍</h2><p>Given a singly linked list, determine if it is a palindrome.<br>给定一个单向链表，判断是否是回文链表</p>
<h3 id="例一-Example-1"><a href="#例一-Example-1" class="headerlink" title="例一 Example 1:"></a>例一 Example 1:</h3><p>Input: 1-&gt;2<br>Output: false</p>
<h3 id="例二-Example-2"><a href="#例二-Example-2" class="headerlink" title="例二 Example 2:"></a>例二 Example 2:</h3><p>Input: 1-&gt;2-&gt;2-&gt;1<br>Output: true</p>
<h3 id="挑战下自己"><a href="#挑战下自己" class="headerlink" title="挑战下自己"></a>挑战下自己</h3><p>Follow up:<br>Could you do it in O(n) time and O(1) space?</p>
<h2 id="简要分析"><a href="#简要分析" class="headerlink" title="简要分析"></a>简要分析</h2><p>首先这是个单向链表，如果是双向的就可以一个从头到尾，一个从尾到头，显然那样就没啥意思了，然后想过要不找到中点，然后用一个栈，把前一半塞进栈里，但是这种其实也比较麻烦，比如长度是奇偶数，然后如何找到中点，这倒是可以借助于双指针，还是比较麻烦，再想一想，回文链表，就跟最开始的一样，链表只有单向的，我用个栈不就可以逆向了么，先把链表整个塞进栈里，然后在一个个 pop 出来跟链表从头开始比较，全对上了就是回文了</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">/**
 * Definition for singly-linked list.
 * public class ListNode &#123;
 *     int val;
 *     ListNode next;
 *     ListNode() &#123;&#125;
 *     ListNode(int val) &#123; this.val = val; &#125;
 *     ListNode(int val, ListNode next) &#123; this.val = val; this.next = next; &#125;
 * &#125;
 */</span>
<span class="token keyword">class</span> <span class="token class-name">Solution</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">isPalindrome</span><span class="token punctuation">(</span><span class="token class-name">ListNode</span> head<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>head <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token class-name">ListNode</span> tail <span class="token operator">=</span> head<span class="token punctuation">;</span>
        <span class="token class-name">LinkedList</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">></span></span> stack <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">LinkedList</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">// 这里就是一个循环，将所有元素依次压入栈</span>
        <span class="token keyword">while</span> <span class="token punctuation">(</span>tail <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            stack<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span>tail<span class="token punctuation">.</span>val<span class="token punctuation">)</span><span class="token punctuation">;</span>
            tail <span class="token operator">=</span> tail<span class="token punctuation">.</span>next<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token comment">// 在逐个 pop 出来，其实这个出来的顺序就等于链表从尾到头遍历，同时跟链表从头到尾遍历进行逐对对比</span>
        <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token operator">!</span>stack<span class="token punctuation">.</span><span class="token function">isEmpty</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>stack<span class="token punctuation">.</span><span class="token function">peekFirst</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> head<span class="token punctuation">.</span>val<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                stack<span class="token punctuation">.</span><span class="token function">pollFirst</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                head <span class="token operator">=</span> head<span class="token punctuation">.</span>next<span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>]]></content>
      <categories>
        <category>Java</category>
        <category>leetcode</category>
        <category>Linked List</category>
        <category>java</category>
        <category>Linked List</category>
      </categories>
      <tags>
        <tag>leetcode</tag>
        <tag>java</tag>
        <tag>题解</tag>
        <tag>Linked List</tag>
      </tags>
  </entry>
  <entry>
    <title>Leetcode 236 二叉树的最近公共祖先(Lowest Common Ancestor of a Binary Tree) 题解分析</title>
    <url>/2021/05/23/Leetcode-236-%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E8%BF%91%E5%85%AC%E5%85%B1%E7%A5%96%E5%85%88-Lowest-Common-Ancestor-of-a-Binary-Tree-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/</url>
    <content><![CDATA[<h3 id="题目介绍"><a href="#题目介绍" class="headerlink" title="题目介绍"></a>题目介绍</h3><p>Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.</p>
<p>According to the <a href="https://en.wikipedia.org/wiki/Lowest_common_ancestor">definition of LCA on Wikipedia</a>: “The lowest common ancestor is defined between two nodes <code>p</code> and <code>q</code> as the lowest node in <code>T</code> that has both <code>p</code> and <code>q</code> as descendants (where we allow <strong>a node to be a descendant of itself</strong>).”</p>
<p>给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。</p>
<p><a href="https://baike.baidu.com/item/%E6%9C%80%E8%BF%91%E5%85%AC%E5%85%B1%E7%A5%96%E5%85%88/8918834?fr=aladdin">百度百科</a>中最近公共祖先的定义为：“对于有根树 <code>T</code> 的两个节点 <code>p</code>、<code>q</code>，最近公共祖先表示为一个节点 <code>x</code>，满足 <code>x</code> 是 <code>p</code>、<code>q</code> 的祖先且 <code>x</code> 的深度尽可能大（<strong>一个节点也可以是它自己的祖先</strong>）。”</p>
<h2 id="代码"><a href="#代码" class="headerlink" title="代码"></a>代码</h2><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">TreeNode</span> <span class="token function">lowestCommonAncestor</span><span class="token punctuation">(</span><span class="token class-name">TreeNode</span> root<span class="token punctuation">,</span> <span class="token class-name">TreeNode</span> p<span class="token punctuation">,</span> <span class="token class-name">TreeNode</span> q<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">// 如果当前节点就是 p 或者是 q 的时候，就直接返回了</span>
        <span class="token comment">// 当没找到，即 root == null 的时候也会返回 null，这是个重要的点</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>root <span class="token operator">==</span> <span class="token keyword">null</span> <span class="token operator">||</span> root <span class="token operator">==</span> p <span class="token operator">||</span> root <span class="token operator">==</span> q<span class="token punctuation">)</span> <span class="token keyword">return</span> root<span class="token punctuation">;</span>
        <span class="token comment">// 在左子树中找 p 和 q</span>
        <span class="token class-name">TreeNode</span> left <span class="token operator">=</span> <span class="token function">lowestCommonAncestor</span><span class="token punctuation">(</span>root<span class="token punctuation">.</span>left<span class="token punctuation">,</span> p<span class="token punctuation">,</span> q<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">// 在右子树中找 p 和 q</span>
        <span class="token class-name">TreeNode</span> right <span class="token operator">=</span> <span class="token function">lowestCommonAncestor</span><span class="token punctuation">(</span>root<span class="token punctuation">.</span>right<span class="token punctuation">,</span> p<span class="token punctuation">,</span> q<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">// 当左边是 null 就直接返回右子树，但是这里不表示右边不是 null，所以这个顺序是不影响的</span>
        <span class="token comment">// 考虑一种情况，如果一个节点的左右子树都是 null，那么其实对于这个节点来说首先两个子树分别调用</span>
        <span class="token comment">// lowestCommonAncestor会在开头就返回 null，那么就是上面 left 跟 right 都是 null，然后走下面的判断的时候</span>
        <span class="token comment">// 其实第一个 if 就返回了 null，如此递归返回就能达到当子树中没有找到 p 或者 q 的时候只返回 null</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>left <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> right<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>right <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> left<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> root<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
<span class="token comment">//        if (right == null) &#123;</span>
<span class="token comment">//            return left;</span>
<span class="token comment">//        &#125; else if (left == null) &#123;</span>
<span class="token comment">//            return right;</span>
<span class="token comment">//        &#125; else &#123;</span>
<span class="token comment">//            return root;</span>
<span class="token comment">//        &#125;</span>
<span class="token comment">//        return left == null ? right : right == null ? left : root;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
]]></content>
      <categories>
        <category>Java</category>
        <category>leetcode</category>
        <category>Lowest Common Ancestor of a Binary Tree</category>
      </categories>
      <tags>
        <tag>leetcode</tag>
        <tag>java</tag>
        <tag>题解</tag>
        <tag>Lowest Common Ancestor of a Binary Tree</tag>
      </tags>
  </entry>
  <entry>
    <title>Leetcode 3 Longest Substring Without Repeating Characters 题解分析</title>
    <url>/2020/09/20/Leetcode-3-Longest-Substring-Without-Repeating-Characters-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/</url>
    <content><![CDATA[<p>又做了个题，看记录是以前用 C++写过的，现在捋一捋思路，用 Java 再写了一下，思路还是比较清晰的，但是边界细节处理得比较差</p>
<h2 id="简要介绍"><a href="#简要介绍" class="headerlink" title="简要介绍"></a>简要介绍</h2><p>Given a string <code>s</code>, find the length of the <strong>longest substring</strong> without repeating characters.</p>
<h2 id="样例"><a href="#样例" class="headerlink" title="样例"></a>样例</h2><h4 id="Example-1"><a href="#Example-1" class="headerlink" title="Example 1:"></a>Example 1:</h4><pre class="line-numbers language-none"><code class="language-none">Input: s &#x3D; &quot;abcabcbb&quot;
Output: 3
Explanation: The answer is &quot;abc&quot;, with the length of 3.<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<h4 id="Example-2"><a href="#Example-2" class="headerlink" title="Example 2:"></a>Example 2:</h4><pre class="line-numbers language-none"><code class="language-none">Input: s &#x3D; &quot;bbbbb&quot;
Output: 1
Explanation: The answer is &quot;b&quot;, with the length of 1.<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<h4 id="Example-3"><a href="#Example-3" class="headerlink" title="Example 3:"></a>Example 3:</h4><pre class="line-numbers language-none"><code class="language-none">Input: s &#x3D; &quot;pwwkew&quot;
Output: 3
Explanation: The answer is &quot;wke&quot;, with the length of 3.
Notice that the answer must be a substring, &quot;pwke&quot; is a subsequence and not a substring.<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="Example-4"><a href="#Example-4" class="headerlink" title="Example 4:"></a>Example 4:</h4><pre class="line-numbers language-none"><code class="language-none">Input: s &#x3D; &quot;&quot;
Output: 0<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>就是一个最长不重复的字符串长度，因为也是中等难度的题，不太需要特别复杂的思考，最基本的就是O(N*N)两重循环，不过显然不太好，万一超时间，还有一种就是线性复杂度的了，这个就是需要搞定一个思路，比如字符串时 <code>a</code>bcdefg<code>a</code>qwrty，比如遍历到第二个<code>a</code>的时候其实不用再从头去遍历了，只要把前面那个<code>a</code>给排除掉，继续往下算就好了</p>
<pre class="line-numbers language-Java" data-language="Java"><code class="language-Java">class Solution &#123;
    Map&lt;String, Integer&gt; counter &#x3D; new HashMap&lt;&gt;();
    public int lengthOfLongestSubstring(String s) &#123;
        int length &#x3D; s.length();
        &#x2F;&#x2F; 当前的长度
        int subStringLength &#x3D; 0;
        &#x2F;&#x2F; 最长的长度
        int maxSubStringLength &#x3D; 0;
        &#x2F;&#x2F; 考虑到重复的位置已经被跳过的情况，即已经在当前长度的字符串范围之前的重复字符不需要回溯
        int lastDuplicatePos &#x3D; -1;
        for (int i &#x3D; 0; i &lt; length; i++) &#123;
            &#x2F;&#x2F; 使用 map 存储字符和上一次出现的位置，如果存在并且大于上一次重复位置
            if (counter.get(String.valueOf(s.charAt(i))) !&#x3D; null &amp;&amp; counter.get(String.valueOf(s.charAt(i))) &gt; lastDuplicatePos) &#123;
                &#x2F;&#x2F; 记录重复位置
                lastDuplicatePos &#x3D; counter.get(String.valueOf(s.charAt(i)));
                &#x2F;&#x2F; 重置不重复子串的长度，减去重复起点
                subStringLength &#x3D; i - counter.get(String.valueOf(s.charAt(i))) - 1;
                &#x2F;&#x2F; 替换当前位置
                counter.replace(String.valueOf(s.charAt(i)), i);
            &#125; else &#123;
                &#x2F;&#x2F; 如果不存在就直接 put
                counter.put(String.valueOf(s.charAt(i)), i);
            &#125;
            &#x2F;&#x2F; 长度累加
            subStringLength++;
            if (subStringLength &gt; maxSubStringLength) &#123;
                &#x2F;&#x2F; 简单替换
                maxSubStringLength &#x3D; subStringLength;
            &#125;
        &#125;
        return maxSubStringLength;
    &#125;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>注释应该写的比较清楚了。</p>
]]></content>
      <categories>
        <category>Java</category>
        <category>leetcode</category>
        <category>java</category>
        <category>字符串 - online</category>
        <category>string</category>
      </categories>
      <tags>
        <tag>leetcode</tag>
        <tag>java</tag>
        <tag>题解</tag>
        <tag>string</tag>
      </tags>
  </entry>
  <entry>
    <title>Leetcode 42 接雨水 (Trapping Rain Water) 题解分析</title>
    <url>/2021/07/04/Leetcode-42-%E6%8E%A5%E9%9B%A8%E6%B0%B4-Trapping-Rain-Water-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/</url>
    <content><![CDATA[<h2 id="题目介绍"><a href="#题目介绍" class="headerlink" title="题目介绍"></a>题目介绍</h2><p>给定 n 个非负整数表示每个宽度为 1 的柱子的高度图，计算按此排列的柱子，下雨之后能接多少雨水。</p>
<h2 id="示例"><a href="#示例" class="headerlink" title="示例"></a>示例</h2><p><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/AggmPZ.jpg"><br><strong>输入</strong>：height = [0,1,0,2,1,0,1,3,2,1,2,1]<br><strong>输出</strong>：6<br><strong>解释</strong>：上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图，在这种情况下，可以接 6 个单位的雨水（蓝色部分表示雨水）。</p>
<h2 id="简单分析"><a href="#简单分析" class="headerlink" title="简单分析"></a>简单分析</h2><p>其实最开始的想法是从左到右扫区间，就是示例中的第一个水槽跟第二个水槽都可以用这个办法解决<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/zCLMbU.png"><br>前面这种是属于右侧比左侧高的情况，对于左侧高右侧低的就不行了，（写这篇的时候想起来可以再反着扫一遍可能可以）<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/tO4tWh.png"><br>所以这个方案不好，贴一下这个方案的代码</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">trap</span><span class="token punctuation">(</span><span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> height<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">int</span> lastLeft <span class="token operator">=</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">;</span>
    <span class="token keyword">int</span> sum <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
    <span class="token keyword">int</span> tempSum <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
    <span class="token keyword">boolean</span> startFlag <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> j <span class="token operator">:</span> height<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>startFlag <span class="token operator">&amp;&amp;</span> j <span class="token operator">&lt;=</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            startFlag <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
            <span class="token keyword">continue</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>j <span class="token operator">>=</span> lastLeft<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            sum <span class="token operator">+=</span> tempSum<span class="token punctuation">;</span>
            tempSum <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
            lastLeft <span class="token operator">=</span> j<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
            tempSum <span class="token operator">+=</span> lastLeft <span class="token operator">-</span> j<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">return</span> sum<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>后面结合网上的解法，其实可以反过来，对于每个格子找左右侧的最大值，取小的那个和当前格子的差值就是这一个的储水量了<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/PXGiCa.png"><br>理解了这种想法，代码其实就不难了</p>
<h2 id="代码"><a href="#代码" class="headerlink" title="代码"></a>代码</h2><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">int</span> n <span class="token operator">=</span> height<span class="token punctuation">.</span>length<span class="token punctuation">;</span>
<span class="token keyword">if</span> <span class="token punctuation">(</span>n <span class="token operator">&lt;=</span> <span class="token number">2</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">// 思路转变下，其实可以对于每一格算储水量，算法就是找到这一格左边的最高点跟这一格右边的最高点，</span>
<span class="token comment">// 比较两侧的最高点，取小的那个，然后再跟当前格子的高度对比，差值就是当前格的储水量</span>
<span class="token keyword">int</span> maxL<span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token keyword">int</span><span class="token punctuation">[</span>n<span class="token punctuation">]</span><span class="token punctuation">;</span>
<span class="token keyword">int</span> maxR<span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token keyword">int</span><span class="token punctuation">[</span>n<span class="token punctuation">]</span><span class="token punctuation">;</span>
<span class="token keyword">int</span> max <span class="token operator">=</span> height<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
maxL<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token comment">// 计算左侧的最高点</span>
<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> n <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    maxL<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">=</span> max<span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>max <span class="token operator">&lt;</span> height<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        max <span class="token operator">=</span> height<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>
max <span class="token operator">=</span> height<span class="token punctuation">[</span>n <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
maxR<span class="token punctuation">[</span>n <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token keyword">int</span> tempSum<span class="token punctuation">,</span> sum <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token comment">// 计算右侧的最高点，并且同步算出来储水量，节省一个循环</span>
<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> n <span class="token operator">-</span> <span class="token number">2</span><span class="token punctuation">;</span> i <span class="token operator">></span> <span class="token number">0</span><span class="token punctuation">;</span> i<span class="token operator">--</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    maxR<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">=</span> max<span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>height<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">></span> max<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        max <span class="token operator">=</span> height<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    tempSum <span class="token operator">=</span> <span class="token class-name">Math</span><span class="token punctuation">.</span><span class="token function">min</span><span class="token punctuation">(</span>maxL<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">,</span> maxR<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token operator">-</span> height<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>tempSum <span class="token operator">></span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        sum <span class="token operator">+=</span> tempSum<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">return</span> sum<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
]]></content>
      <categories>
        <category>Java</category>
        <category>leetcode</category>
      </categories>
      <tags>
        <tag>leetcode</tag>
        <tag>java</tag>
        <tag>dp</tag>
        <tag>代码题解</tag>
        <tag>Trapping Rain Water</tag>
        <tag>接雨水</tag>
        <tag>Leetcode 42</tag>
      </tags>
  </entry>
  <entry>
    <title>Leetcode 48 旋转图像(Rotate Image) 题解分析</title>
    <url>/2021/05/01/Leetcode-48-%E6%97%8B%E8%BD%AC%E5%9B%BE%E5%83%8F-Rotate-Image-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/</url>
    <content><![CDATA[<h3 id="题目介绍"><a href="#题目介绍" class="headerlink" title="题目介绍"></a>题目介绍</h3><p>You are given an n x n 2D <code>matrix</code> representing an image, rotate the image by 90 degrees (clockwise).</p>
<p>You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. <strong>DO NOT</strong> allocate another 2D matrix and do the rotation.<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/p8lf4Y.png"><br>如图，这道题以前做过，其实一看有点蒙，好像规则很容易描述，但是代码很难写，因为要类似于贪吃蛇那样，后来想着应该会有一些特殊的技巧，比如翻转等</p>
<h3 id="代码"><a href="#代码" class="headerlink" title="代码"></a>代码</h3><p>直接上码</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">rotate</span><span class="token punctuation">(</span><span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token punctuation">]</span> matrix<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">// 这里真的傻了，长宽应该是一致的，所以取一次就够了</span>
        <span class="token keyword">int</span> lengthX <span class="token operator">=</span> matrix<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">.</span>length<span class="token punctuation">;</span>
        <span class="token keyword">int</span> lengthY <span class="token operator">=</span> matrix<span class="token punctuation">.</span>length<span class="token punctuation">;</span>
        <span class="token keyword">int</span> temp<span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>lengthY <span class="token operator">-</span> <span class="token punctuation">(</span>lengthY <span class="token operator">%</span> <span class="token number">2</span><span class="token punctuation">)</span> <span class="token operator">/</span> <span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">// 这里除错了，应该是减掉余数再除 2</span>
<span class="token comment">//        for (int i = 0; i &lt; lengthY - (lengthY % 2) / 2; i++) &#123;</span>
        <span class="token comment">/**
         * 1 2 3             7 8 9
         * 4 5 6     =>      4 5 6     先沿着 4 5 6 上下交换
         * 7 8 9             1 2 3
         */</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token punctuation">(</span>lengthY <span class="token operator">-</span> <span class="token punctuation">(</span>lengthY <span class="token operator">%</span> <span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token operator">/</span> <span class="token number">2</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> j <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> j <span class="token operator">&lt;</span> lengthX<span class="token punctuation">;</span> j<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                temp <span class="token operator">=</span> matrix<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">[</span>j<span class="token punctuation">]</span><span class="token punctuation">;</span>
                matrix<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">[</span>j<span class="token punctuation">]</span> <span class="token operator">=</span> matrix<span class="token punctuation">[</span>lengthY<span class="token operator">-</span>i<span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">[</span>j<span class="token punctuation">]</span><span class="token punctuation">;</span>
                matrix<span class="token punctuation">[</span>lengthY<span class="token operator">-</span>i<span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">[</span>j<span class="token punctuation">]</span> <span class="token operator">=</span> temp<span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token comment">/**
         * 7 8 9               7 4 1
         * 4 5 6     =>        8 5 2   这里再沿着 7 5 3 这条对角线交换
         * 1 2 3               9 6 3
         */</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> lengthX<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> j <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> j <span class="token operator">&lt;=</span> i<span class="token punctuation">;</span> j<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>i <span class="token operator">==</span> j<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">continue</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
                temp <span class="token operator">=</span> matrix<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">[</span>j<span class="token punctuation">]</span><span class="token punctuation">;</span>
                matrix<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">[</span>j<span class="token punctuation">]</span> <span class="token operator">=</span> matrix<span class="token punctuation">[</span>j<span class="token punctuation">]</span><span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">;</span>
                matrix<span class="token punctuation">[</span>j<span class="token punctuation">]</span><span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">=</span> temp<span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>还没到可以直接归纳题目类型的水平，主要是几年前做过，可能有那么点模糊的记忆，当然应该也有直接转的方法</p>
]]></content>
      <categories>
        <category>Java</category>
        <category>leetcode</category>
        <category>Rotate Image</category>
      </categories>
      <tags>
        <tag>leetcode</tag>
        <tag>java</tag>
        <tag>题解</tag>
        <tag>Rotate Image</tag>
        <tag>矩阵</tag>
      </tags>
  </entry>
  <entry>
    <title>leetcode no.3</title>
    <url>/2015/04/15/Leetcode-No-3/</url>
    <content><![CDATA[<p>**Longest Substring Without Repeating Characters **</p>
<span id="more"></span>
<h3 id="description"><a href="#description" class="headerlink" title="description"></a>description</h3><p>Given a string, find the length of the longest substring without repeating characters.<br>For example, the longest substring without repeating letters for “abcabcbb” is “abc”,<br>which the length is 3. For “bbbbb” the longest substring is “b”, with the length of 1.  </p>
<h3 id="分析"><a href="#分析" class="headerlink" title="分析"></a>分析</h3><p><a href="http://www.cnblogs.com/dollarzhaole/p/3155712.html">源码</a>这次是参考了这个代码，<br>tail 表示的当前子串的起始点位置，tail从-1开始就包括的串的长度是1的边界。其实我<br>也是猜的（逃</p>
<pre class="line-numbers language-C++" data-language="C++"><code class="language-C++">int ct[256];
    memset(ct, -1, sizeof(ct));
	int tail &#x3D; -1;
	int max &#x3D; 0;
	for (int i &#x3D; 0; i &lt; s.size(); i++)&#123;
		if (ct[s[i]] &gt; tail)
			tail &#x3D; ct[s[i]];
		if (i - tail &gt; max)
			max &#x3D; i - tail;
		ct[s[i]] &#x3D; i;
	&#125;
	return max;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
]]></content>
      <categories>
        <category>leetcode</category>
      </categories>
      <tags>
        <tag>leetcode</tag>
        <tag>c++</tag>
      </tags>
  </entry>
  <entry>
    <title>Linux 下 grep 命令的一点小技巧</title>
    <url>/2020/08/06/Linux-%E4%B8%8B-grep-%E5%91%BD%E4%BB%A4%E7%9A%84%E4%B8%80%E7%82%B9%E5%B0%8F%E6%8A%80%E5%B7%A7/</url>
    <content><![CDATA[<p>用了比较久的 grep 命令，其实都只是用了最最基本的功能来查日志，</p>
<p>譬如</p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell">
grep &#39;xxx&#39; xxxx.log
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>然后有挺多情况比如想要找日志里带一些符号什么的，就需要用到一些特殊的</p>
<p>比如这样<code>\&quot;userId\&quot;:\&quot;123456\&quot;</code>，因为比如用户 ID 有时候会跟其他的 id 一样，只用具体的值 123456 来查的话干扰信息太多了，如果直接这样</p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell">
grep &#39;\&quot;userId\&quot;:\&quot;123456\&quot;&#39; xxxx.log
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>好像不行，盲猜就是符号的问题，特别是<code>\</code>和<code>&quot;</code>这两个，</p>
<p>之前一直是想试一下，但是没成功，昨天在排查一个问题的时候发现了，只要把这些都转义了就行了</p>
<p><code>grep &#39;\\\&quot;userId\\\&quot;:\\\&quot;123456\\\&quot;&#39; xxxx.log</code></p>
<p><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/sUdv2K.png"></p>
]]></content>
      <categories>
        <category>Linux</category>
        <category>小技巧</category>
        <category>命令</category>
        <category>grep</category>
        <category>grep</category>
        <category>查日志</category>
      </categories>
      <tags>
        <tag>linux</tag>
        <tag>grep</tag>
        <tag>转义</tag>
      </tags>
  </entry>
  <entry>
    <title>MFC 模态对话框</title>
    <url>/2014/12/24/MFC%20%E6%A8%A1%E6%80%81%E5%AF%B9%E8%AF%9D%E6%A1%86/</url>
    <content><![CDATA[<pre class="line-numbers language-C++" data-language="C++"><code class="language-C++">void CTestDialog::OnBnClickedOk() 
&#123;
	CString m_SrcTest;
	int nIndex &#x3D; m_CbTest.GetCurSel(); 
	m_CbTest.GetLBText(nIndex, m_SrcTest);  
	OnOK();
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>模态对话框弹出确定后，在弹出对话框时新建的类及其变量会存在，但是对于其中的控件<br>对象无法调用函数，即如果要在主对话框中获得弹出对话框的Combo box选中值的话，需<br>要在弹出  对话框的确定函数内将其值取出，赋值给弹出对话框的公有变量，这样就可以<br>在主对话框类得到值。  </p>
]]></content>
      <categories>
        <category>C++</category>
      </categories>
      <tags>
        <tag>c++</tag>
        <tag>mfc</tag>
      </tags>
  </entry>
  <entry>
    <title>Maven实用小技巧</title>
    <url>/2020/02/16/Maven%E5%AE%9E%E7%94%A8%E5%B0%8F%E6%8A%80%E5%B7%A7/</url>
    <content><![CDATA[<p>Maven 翻译为”专家”、”内行”，是 Apache 下的一个纯 Java 开发的开源项目。基于项目对象模型（缩写：POM）概念，Maven利用一个中央信息片断能管理一个项目的构建、报告和文档等步骤。</p>
<p>Maven 是一个项目管理工具，可以对 Java 项目进行构建、依赖管理。</p>
<p>Maven 也可被用于构建和管理各种项目，例如 C#，Ruby，Scala 和其他语言编写的项目。Maven 曾是 Jakarta 项目的子项目，现为由 Apache 软件基金会主持的独立 Apache 项目。</p>
<p>maven也是我们日常项目中实用的包管理工具，相比以前需要用把包下载下来，放进 lib 中，在平时工作中使用的话，其实像 idea 这样的 ide 工具都会自带 maven 工具和插件</p>
<h3 id="maven的基本操作"><a href="#maven的基本操作" class="headerlink" title="maven的基本操作"></a>maven的基本操作</h3><ul>
<li><code>mvn -v</code><br>  查看 maven 信息</li>
<li><code>mvn compile</code><br>  将 Java 编译成 class 文件</li>
<li><code>mvn test</code><br>  执行 test 包下的测试用例</li>
<li><code>mvn package</code><br>  将项目打成 jar 包</li>
<li><code>mvn clean</code><br>  删除package 在 target 目录下面打出来的 jar 包和 target 目录</li>
<li><code>mvn install</code><br>  将打出来的 jar 包复制到 maven 的本地仓库里</li>
<li><code>mvn deploy</code><br>  将打出来的 jar 包上传到远程仓库里</li>
</ul>
<h3 id="与-composer-对比"><a href="#与-composer-对比" class="headerlink" title="与 composer 对比"></a>与 composer 对比</h3><p>因为我也是个 PHP 程序员，所以对比一下两种语言，很容易想到在 PHP 的 composer 跟 Java 的 maven 是比较类似的作用，有一点两者是非常相似的，就是原仓库都是因为某些原因连接拉取都会很慢，所以像 composer 会有一些国内源，前阵子阿里也出了一个，类似的 maven 一般也会使用阿里的镜像仓库，通过在 setting.xml 文件中的设置</p>
<pre class="line-numbers language-none"><code class="language-none">&lt;mirrors&gt;
    &lt;mirror&gt;
        &lt;id&gt;aliyun&lt;&#x2F;id&gt;
        &lt;name&gt;aliyun maven&lt;&#x2F;name&gt;
        &lt;url&gt;http:&#x2F;&#x2F;maven.aliyun.com&#x2F;nexus&#x2F;content&#x2F;groups&#x2F;public&#x2F;&lt;&#x2F;url&gt;
        &lt;mirrorOf&gt;central&lt;&#x2F;mirrorOf&gt;
    &lt;&#x2F;mirror&gt; 
&lt;&#x2F;mirrors&gt;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这算是个尴尬的共同点，然后因为 PHP 是解释型脚本语言，所以 php 打出来的 composer 包其实就是个 php 代码包，使用SPL Autoload等方式加载代码包，maven 包则是经过编译的 class 包，还有一点是 composer 也可以直接使用 github 地址作为包代码的拉取源，这点也是比较大的区别，maven使用 pom 文件管理依赖</p>
<h3 id="maven-的个人小技巧"><a href="#maven-的个人小技巧" class="headerlink" title="maven 的个人小技巧"></a>maven 的个人小技巧</h3><ul>
<li>maven 拉取依赖时，同时将 snapshot 也更新了，就是 <code>mvn compile</code>加个<code>-U</code>参数，如果还不行就需要将本地仓库的 snapshot 删掉，<br>这个命令的 help 命令解释是 -U,–update-snapshots Forces a check for missing releases and updated snapshots on<br>remote repositories，这个在日常使用中还是很经常使用的</li>
<li>maven 出现依赖冲突的时候的解决方法<br>首先是依赖分析，使用<code>mvn dependency:tree</code>分析下依赖关系，如果要找具体某个包的依赖引用关系可以使用<code>mvn dependency:tree -Dverbose -Dincludes=org.springframework:spring-webmvc</code>命令进行分析，如果发现有冲突的依赖关系，本身 maven 中依赖引用有相对的顺序，大致来说是引用路径短的优先，pom 文件中定义的顺序优先，如果要把冲突的包排除掉可以在 pom 中用<pre class="line-numbers language-none"><code class="language-none">&lt;exclusions&gt;
  &lt;exclusion&gt;
      &lt;groupId&gt;ch.qos.logback&lt;&#x2F;groupId&gt;
      &lt;artifactId&gt;logback-classic&lt;&#x2F;artifactId&gt;
  &lt;&#x2F;exclusion&gt;
&lt;&#x2F;exclusions&gt;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
将冲突的包排除掉</li>
<li>maven 依赖的 jdk 版本管理<br>前面介绍的<code>mvn -v</code>可以查看 maven 的安装信息<br>比如<pre class="line-numbers language-none"><code class="language-none">Apache Maven 3.6.3 (cecedd343002696d0abb50b32b541b8a6ba2883f)
Maven home: &#x2F;usr&#x2F;local&#x2F;Cellar&#x2F;maven&#x2F;3.6.3_1&#x2F;libexec
Java version: 1.8.0_201, vendor: Oracle Corporation, runtime: &#x2F;Library&#x2F;Java&#x2F;JavaVirtualMachines&#x2F;jdk1.8.0_201.jdk&#x2F;Contents&#x2F;Home&#x2F;jre
Default locale: zh_CN, platform encoding: UTF-8
OS name: &quot;mac os x&quot;, version: &quot;10.14.6&quot;, arch: &quot;x86_64&quot;, family: &quot;mac&quot;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
这里可以看到用了 mac 自带的 jdk1.8，结合我之前碰到的一个问题，因为使用 homebrew 升级了 gradle，而 gradle 又依赖了 jdk13，因为这个 mvn 的 Java version 也变成 jdk13 了，然后 mvn 编译的时候出现了 <code>java.lang.ExceptionInInitializerError: com.sun.tools.javac.code.TypeTags</code>这个问题，所以需要把这个版本给改回来，但是咋改呢，网上搜来的一大堆都是在 pom 文件里的<br>source和 target 版本<pre class="line-numbers language-none"><code class="language-none">&lt;build&gt;
  &lt;plugins&gt;
&lt;plugin&gt;
	&lt;groupId&gt;org.apache.maven.plugins&lt;&#x2F;groupId&gt;
	&lt;artifactId&gt;maven-compiler-plugin&lt;&#x2F;artifactId&gt;
	&lt;configuration&gt;
		&lt;source&gt;1.8&lt;&#x2F;source&gt;
		&lt;target&gt;1.8&lt;&#x2F;target&gt;
		&lt;encoding&gt;UTF-8&lt;&#x2F;encoding&gt;
	&lt;&#x2F;configuration&gt;
&lt;&#x2F;plugin&gt;
  &lt;&#x2F;plugins&gt;
&lt;build&gt;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
或者修改 maven 的 setting.xml中的<pre class="line-numbers language-none"><code class="language-none">&lt;profiles&gt;
      &lt;profile&gt;
          &lt;id&gt;ngmm-nexus&lt;&#x2F;id&gt;
        &lt;activation&gt;
          &lt;jdk&gt;1.8&lt;&#x2F;jdk&gt;
        &lt;&#x2F;activation&gt;
        &lt;properties&gt;
          &lt;maven.compiler.source&gt;1.8&lt;&#x2F;maven.compiler.source&gt;
          &lt;maven.compiler.target&gt;1.8&lt;&#x2F;maven.compiler.target&gt;
          &lt;maven.compiler.compilerVersion&gt;1.8&lt;&#x2F;maven.compiler.compilerVersion&gt;
      &lt;&#x2F;properties&gt;
      &lt;&#x2F;profile&gt;
&lt;&#x2F;profiles&gt;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
但是这些都没啥用啊，真正有办法的是建个 <code>.mavenrc</code>，这个顾名思义就是 maven 的资源文件，类似于 <code>.bashrc</code>和<code>.zshrc</code>，在里面添加 MAVEN_HOME 和 JAVA_HOME,然后执行 <code>source .mavenrc</code>就 OK 啦</li>
</ul>
]]></content>
      <categories>
        <category>Java</category>
        <category>Maven</category>
      </categories>
      <tags>
        <tag>Java</tag>
        <tag>Maven</tag>
      </tags>
  </entry>
  <entry>
    <title>Number of 1 Bits</title>
    <url>/2015/03/11/Number-Of-1-Bits/</url>
    <content><![CDATA[<h3 id="Number-of-1-Bits"><a href="#Number-of-1-Bits" class="headerlink" title="Number of 1 Bits "></a><a href="https://leetcode.com/problems/number-of-1-bits/">Number of 1 Bits </a></h3><h4 id="Write-a-function-that-takes-an-unsigned-integer-and-returns-the-number-of-’1’-bits-it-has-also-known-as-the-Hamming-weight-For-example-the-32-bit-integer-‘11’-has-binary-representation-00000000000000000000000000001011-so-the-function-should-return-3"><a href="#Write-a-function-that-takes-an-unsigned-integer-and-returns-the-number-of-’1’-bits-it-has-also-known-as-the-Hamming-weight-For-example-the-32-bit-integer-‘11’-has-binary-representation-00000000000000000000000000001011-so-the-function-should-return-3" class="headerlink" title="Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight). For example, the 32-bit integer ‘11’ has binary representation  00000000000000000000000000001011, so the function should return 3."></a>Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight). For example, the 32-bit integer ‘11’ has binary representation  <code>00000000000000000000000000001011</code>, so the function should return 3.</h4><span id="more"></span>

<h3 id="分析"><a href="#分析" class="headerlink" title="分析"></a>分析</h3><p>从1位到2位到4位逐步的交换</p>
<hr>
<h3 id="code"><a href="#code" class="headerlink" title="code"></a>code</h3><pre class="line-numbers language-C++" data-language="C++"><code class="language-C++">int hammingWeight(uint32_t n) &#123;
        const uint32_t m1  &#x3D; 0x55555555; &#x2F;&#x2F;binary: 0101...  
        const uint32_t m2  &#x3D; 0x33333333; &#x2F;&#x2F;binary: 00110011..  
        const uint32_t m4  &#x3D; 0x0f0f0f0f; &#x2F;&#x2F;binary:  4 zeros,  4 ones ...  
        const uint32_t m8  &#x3D; 0x00ff00ff; &#x2F;&#x2F;binary:  8 zeros,  8 ones ...  
        const uint32_t m16 &#x3D; 0x0000ffff; &#x2F;&#x2F;binary: 16 zeros, 16 ones ...  
        
        n &#x3D; (n &amp; m1 ) + ((n &gt;&gt;  1) &amp; m1 ); &#x2F;&#x2F;put count of each  2 bits into those  2 bits   
        n &#x3D; (n &amp; m2 ) + ((n &gt;&gt;  2) &amp; m2 ); &#x2F;&#x2F;put count of each  4 bits into those  4 bits   
        n &#x3D; (n &amp; m4 ) + ((n &gt;&gt;  4) &amp; m4 ); &#x2F;&#x2F;put count of each  8 bits into those  8 bits   
        n &#x3D; (n &amp; m8 ) + ((n &gt;&gt;  8) &amp; m8 ); &#x2F;&#x2F;put count of each 16 bits into those 16 bits   
        n &#x3D; (n &amp; m16) + ((n &gt;&gt; 16) &amp; m16); &#x2F;&#x2F;put count of each 32 bits into those 32 bits   
        return n; 

&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>]]></content>
      <categories>
        <category>leetcode</category>
      </categories>
      <tags>
        <tag>leetcode</tag>
        <tag>c++</tag>
      </tags>
  </entry>
  <entry>
    <title>Path Sum</title>
    <url>/2015/01/04/Path-Sum/</url>
    <content><![CDATA[<h3 id="problem"><a href="#problem" class="headerlink" title="problem"></a>problem</h3><p>Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.</p>
<span id="more"></span>
<p>For example:<br>Given the below binary tree and sum = 22,</p>
<pre class="line-numbers language-none"><code class="language-none">      5
     &#x2F; \
    4   8
   &#x2F;   &#x2F; \
  11  13  4
 &#x2F;  \      \
7    2      1<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>return true, as there exist a root-to-leaf path 5-&gt;4-&gt;11-&gt;2 which sum is 22.</p>
<h3 id="Analysis"><a href="#Analysis" class="headerlink" title="Analysis"></a>Analysis</h3><p>using simple deep first search</p>
<h3 id="code"><a href="#code" class="headerlink" title="code"></a>code</h3><pre class="line-numbers language-C++" data-language="C++"><code class="language-C++">&#x2F;*
  Definition for binary tree
  struct TreeNode &#123;
      int val;
      TreeNode *left;
      TreeNode *right;
      TreeNode(int x) : val(x), left(NULL), right(NULL)&#125;
  &#125;;
 *&#x2F;
class Solution &#123;
public:
    bool deep_first_search(TreeNode *node, int sum, int curSum)
    &#123;
        if (node &#x3D;&#x3D; NULL)
            return false;
        
        if (node-&gt;left &#x3D;&#x3D; NULL &amp;&amp; node-&gt;right &#x3D;&#x3D; NULL)
            return curSum + node-&gt;val &#x3D;&#x3D; sum;
               
        return deep_first_search(node-&gt;left, sum, curSum + node-&gt;val) || deep_first_search(node-&gt;right, sum, curSum + node-&gt;val);
    &#125;
    
    bool hasPathSum(TreeNode *root, int sum) &#123;
        &#x2F;&#x2F; Start typing your C&#x2F;C++ solution below
        &#x2F;&#x2F; DO NOT write int main() function
        return deep_first_search(root, sum, 0);
    &#125;
&#125;;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
]]></content>
      <categories>
        <category>leetcode</category>
      </categories>
      <tags>
        <tag>leetcode</tag>
        <tag>c++</tag>
      </tags>
  </entry>
  <entry>
    <title>Redis_分布式锁</title>
    <url>/2019/12/10/Redis-Part-1/</url>
    <content><![CDATA[<p>今天看了一下 <code>redis</code> 分布式锁 <code>redlock</code> 的实现，简单记录下，</p>
<h2 id="加锁"><a href="#加锁" class="headerlink" title="加锁"></a>加锁</h2><p>原先我对 <code>redis</code> 锁的概念就是加锁使用 <code>setnx</code>，解锁使用 <code>lua</code> 脚本，但是 <code>setnx</code> 具体是啥，<code>lua</code> 脚本是啥不是很清楚<br>首先简单思考下这个问题，首先为啥不是先 <code>get</code> 一下 <code>key</code> 存不存在，然后再 <code>set</code> 一个 <code>key value</code>，因为加锁这个操作我们是要保证两点，一个是不能中途被打断，也就是说要原子性，如果是先 <code>get</code> 一下 <code>key</code>，如果不存在再 <code>set</code> 值的话，那就不是原子操作了；第二个是可不可以直接 <code>set</code> 值呢，显然不行，锁要保证唯一性，有且只能有一个线程或者其他应用单位获得该锁，正好 <code>setnx</code> 给了我们这种原子命令</p>
<p>然后是 <code>setnx</code> 的键和值分别是啥，键比较容易想到是要锁住的资源，比如 <code>user_id</code>, 这里有个我自己之前比较容易陷进去的误区，但是这个误区后<br>面再说，这里其实是把<code>user_id</code> 作为要锁住的资源，在我获得锁的时候别的线程不允许操作，以此保证业务的正确性，不会被多个线程同时修改，确定了键，再来看看值是啥，其实原先我认为值是啥都没关系，我只要锁住了，光键就够我用了，但是考虑下多个线程的问题，如果我这个线程加了锁，然后我因为 <code>gc</code> 停顿等原因卡死了，这个时候<code>redis</code> 的锁或者说就是 <code>redis</code> 的缓存已经过期了，这时候另一个线程获得锁成功，然后我这个线程又活过来了，然后我就仍然认为我拿着锁，我去对数据进行修改或者释放锁，是不是就出现问题了，所以是不是我们还需要一个东西来区分这个锁是哪个线程加的，所以我们可以将值设置成为一个线程独有识别的值，至少在相对长的一段时间内不会重复。</p>
<p>上面其实还有两个问题，一个是当 <code>gc</code> 超时时，我这个线程如何知道我手里的锁已经过期了，一种方法是我在加好锁之后就维护一个超时时间，这里其实还有个问题，不过跟第二个问题相关，就一起说了，就是设置超时时间，有些对于不是锁的 <code>redis</code> 缓存操作可以是先设置好值，然后在设置过期时间，那么这就又有上面说到的不是原子性的问题，那么就需要在同一条指令里把超时时间也设置了，幸好 <code>redis</code> 提供了这种支持</p>
<pre class="line-numbers language-none"><code class="language-none">SET resource_name my_random_value NX PX 30000<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>这里借鉴一下解释下，<code>resource_name</code>就是 key，代表要锁住的东西，<code>my_random_value</code>就是识别我这个线程的，<code>NX</code>代表只有在不存在的时候才设置，然后<code>PX 30000</code>表示超时时间是 30秒自动过期</p>
<p>PS：记录下我原先有的一个误区，是不是要用 key 来区分加锁的线程，这样只有一个用处，就是自身线程可以识别是否是自己加的锁，但是最大的问题是别的线程不知道，其实这个用户的出发点是我在担心前面提过的一个问题，就是当 gc 停顿后，我要去判断当前的这个锁是否是我加的，还有就是当释放锁的时候，如果保证不会错误释放了其他线程加的锁，但是这样附带很多其他问题，最大的就是其他线程怎么知道能不能加这个锁。</p>
<h2 id="解锁"><a href="#解锁" class="headerlink" title="解锁"></a>解锁</h2><p>当线程在锁过期之前就处理完了业务逻辑，那就可以提前释放这个锁，那么提前释放要怎么操作，直接<code>del key</code>显然是不行的，因为这样就是我前面想用线程随机值加资源名作为锁的初衷，我不能去释放别的线程加的锁，那么我要怎么办呢，先 <code>get</code> 一下看是不是我的？那又变成非原子的操作了，幸好redis 也考虑到了这个问题，给了<code>lua</code> 脚本来操作这种</p>
<pre class="line-numbers language-lua" data-language="lua"><code class="language-lua"><span class="token keyword">if</span> redis<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span><span class="token string">"get"</span><span class="token punctuation">,</span>KEYS<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token operator">==</span> ARGV<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token keyword">then</span>
    <span class="token keyword">return</span> redis<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span><span class="token string">"del"</span><span class="token punctuation">,</span>KEYS<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span>
<span class="token keyword">else</span>
    <span class="token keyword">return</span> <span class="token number">0</span>
<span class="token keyword">end</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这里的<code>KEYS[1]</code>就是前面加锁的<code>resource_name</code>,<code>ARGV[1]</code>就是线程的随机值<code>my_random_value</code></p>
<h2 id="多节点"><a href="#多节点" class="headerlink" title="多节点"></a>多节点</h2><p>前面说的其实是单节点 <code>redis</code> 作为分布式锁的情况，那么当我们的 <code>redis</code> 有多节点的情况呢，如果多节点下处于加锁或者解锁或者锁有效情况下<br><code>redis</code> 的某个节点宕掉了怎么办，这里就有一些需要思考的地方，是否单独搞一个单节点的 <code>redis</code>作为分布式锁专用的，但是如果这个单节点的挂了呢，还有就是成本问题，所以我们需要一个多节点的分布式锁方案<br>这里就引出了开头说到的<code>redlock</code>，这个可是 <code>redis</code>的作者写的, 他的加锁过程是分以下几步去做这个事情</p>
<ul>
<li>获取当前时间（毫秒数）。</li>
<li>按顺序依次向N个Redis节点执行获取锁的操作。这个获取操作跟前面基于单Redis节点的获取锁的过程相同，包含随机字符串my_random_value，也包含过期时间(比如PX 30000，即锁的有效时间)。为了保证在某个Redis节点不可用的时候算法能够继续运行，这个获取锁的操作还有一个超时时间(time out)，它要远小于锁的有效时间（几十毫秒量级）。客户端在向某个Redis节点获取锁失败以后，应该立即尝试下一个Redis节点。这里的失败，应该包含任何类型的失败，比如该Redis节点不可用，或者该Redis节点上的锁已经被其它客户端持有（注：Redlock原文中这里只提到了Redis节点不可用的情况，但也应该包含其它的失败情况）。</li>
<li>计算整个获取锁的过程总共消耗了多长时间，计算方法是用当前时间减去第1步记录的时间。如果客户端从大多数Redis节点（&gt;= N/2+1）成功获取到了锁，并且获取锁总共消耗的时间没有超过锁的有效时间(lock validity time)，那么这时客户端才认为最终获取锁成功；否则，认为最终获取锁失败。</li>
<li>如果最终获取锁成功了，那么这个锁的有效时间应该重新计算，它等于最初的锁的有效时间减去第3步计算出来的获取锁消耗的时间。</li>
<li>如果最终获取锁失败了（可能由于获取到锁的Redis节点个数少于N/2+1，或者整个获取锁的过程消耗的时间超过了锁的最初有效时间），那么客户端应该立即向所有Redis节点发起释放锁的操作（即前面介绍的Redis Lua脚本）。<br>释放锁的过程比较简单：客户端向所有Redis节点发起释放锁的操作，不管这些节点当时在获取锁的时候成功与否。这里为什么要向所有的节点发送释放锁的操作呢，这里是因为有部分的节点的失败原因可能是加锁时阻塞，加锁成功的结果没有及时返回，所以为了防止这种情况还是需要向所有发起这个释放锁的操作。<br>初步记录就先到这。</li>
</ul>
]]></content>
      <categories>
        <category>Redis</category>
        <category>Distributed Lock</category>
        <category>C</category>
        <category>Redis</category>
      </categories>
      <tags>
        <tag>C</tag>
        <tag>Redis</tag>
        <tag>Distributed Lock</tag>
        <tag>分布式锁</tag>
      </tags>
  </entry>
  <entry>
    <title>Reverse Bits</title>
    <url>/2015/03/11/Reverse-Bits/</url>
    <content><![CDATA[<h3 id="Reverse-Bits"><a href="#Reverse-Bits" class="headerlink" title="Reverse Bits "></a><a href="https://leetcode.com/problems/reverse-bits/">Reverse Bits </a></h3><h4 id="Reverse-bits-of-a-given-32-bits-unsigned-integer"><a href="#Reverse-bits-of-a-given-32-bits-unsigned-integer" class="headerlink" title="Reverse bits of a given 32 bits unsigned integer."></a>Reverse bits of a given 32 bits unsigned integer.</h4><p>For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).</p>
<span id="more"></span>
<p>Follow up:<br>If this function is called many times, how would you optimize it?</p>
<hr>
<h3 id="code"><a href="#code" class="headerlink" title="code"></a>code</h3><pre class="line-numbers language-C++" data-language="C++"><code class="language-C++">class Solution &#123;
public:
    uint32_t reverseBits(uint32_t n) &#123;
        n &#x3D; ((n &gt;&gt; 1) &amp; 0x55555555) | ((n &amp; 0x55555555) &lt;&lt; 1);
        n &#x3D; ((n &gt;&gt; 2) &amp; 0x33333333) | ((n &amp; 0x33333333) &lt;&lt; 2);
        n &#x3D; ((n &gt;&gt; 4) &amp; 0x0f0f0f0f) | ((n &amp; 0x0f0f0f0f) &lt;&lt; 4);
        n &#x3D; ((n &gt;&gt; 8) &amp; 0x00ff00ff) | ((n &amp; 0x00ff00ff) &lt;&lt; 8);
        n &#x3D; ((n &gt;&gt; 16) &amp; 0x0000ffff) | ((n &amp; 0x0000ffff) &lt;&lt; 16);
        return n;
    &#125;
&#125;;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
]]></content>
      <categories>
        <category>leetcode</category>
      </categories>
      <tags>
        <tag>leetcode</tag>
        <tag>c++</tag>
      </tags>
  </entry>
  <entry>
    <title>Reverse Integer</title>
    <url>/2015/03/13/Reverse-Integer/</url>
    <content><![CDATA[<h3 id="Reverse-Integer"><a href="#Reverse-Integer" class="headerlink" title="Reverse Integer"></a><a href="https://leetcode.com/problems/reverse-integer/">Reverse Integer</a></h3><h4 id="Reverse-digits-of-an-integer"><a href="#Reverse-digits-of-an-integer" class="headerlink" title="Reverse digits of an integer."></a>Reverse digits of an integer.</h4><p>Example1: x = 123, return 321<br>Example2: x = -123, return -321</p>
<span id="more"></span>
<h4 id="spoilers"><a href="#spoilers" class="headerlink" title="spoilers"></a>spoilers</h4><p>Have you thought about this?<br>Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!</p>
<p>If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100.</p>
<p>Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?</p>
<p>For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.</p>
<hr>
<h3 id="code"><a href="#code" class="headerlink" title="code"></a>code</h3><pre class="line-numbers language-C++" data-language="C++"><code class="language-C++">class Solution &#123;
public:
    int reverse(int x) &#123;

        int max &#x3D; 1 &lt;&lt; 31 - 1;
        int ret &#x3D; 0;
        max &#x3D; (max - 1) * 2 + 1;
        int min &#x3D; 1 &lt;&lt; 31;
        if(x &lt; 0)
            while(x !&#x3D; 0)&#123;
                if(ret &lt; (min - x % 10) &#x2F; 10)
                    return 0;
                ret &#x3D; ret * 10 + x % 10;
                x &#x3D; x &#x2F; 10;
            &#125;
        else
            while(x !&#x3D; 0)&#123;
               if(ret &gt; (max -x % 10) &#x2F; 10)
                    return 0;
                ret &#x3D; ret * 10 + x % 10;
                x &#x3D; x &#x2F; 10;
            &#125;
        return ret;
    &#125;
&#125;;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
]]></content>
      <categories>
        <category>leetcode</category>
      </categories>
      <tags>
        <tag>leetcode</tag>
        <tag>c++</tag>
      </tags>
  </entry>
  <entry>
    <title>two sum</title>
    <url>/2015/01/14/Two-Sum/</url>
    <content><![CDATA[<h3 id="problem"><a href="#problem" class="headerlink" title="problem"></a>problem</h3><p>Given an array of integers, find two numbers such that they add up to a specific target number.</p>
<p>The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.</p>
<span id="more"></span>
<p>You may assume that each input would have exactly one solution.</p>
<p><strong>Input</strong>: numbers={2, 7, 11, 15}, target=9<br><strong>Output</strong>: index1=1, index2=2</p>
<h3 id="code"><a href="#code" class="headerlink" title="code"></a>code</h3><pre class="line-numbers language-c++" data-language="c++"><code class="language-c++">struct Node
&#123;
    int num, pos;
&#125;;
bool cmp(Node a, Node b)
&#123;
    return a.num &lt; b.num;
&#125;
class Solution &#123;
public:
    vector&lt;int&gt; twoSum(vector&lt;int&gt; &amp;numbers, int target) &#123;
        &#x2F;&#x2F; Start typing your C&#x2F;C++ solution below
        &#x2F;&#x2F; DO NOT write int main() function
        vector&lt;int&gt; result;
        vector&lt;Node&gt; array;
        for (int i &#x3D; 0; i &lt; numbers.size(); i++)
        &#123;
            Node temp;
            temp.num &#x3D; numbers[i];
            temp.pos &#x3D; i;
            array.push_back(temp);
        &#125;

        sort(array.begin(), array.end(), cmp);
        for (int i &#x3D; 0, j &#x3D; array.size() - 1; i !&#x3D; j;)
        &#123;
            int sum &#x3D; array[i].num + array[j].num;
            if (sum &#x3D;&#x3D; target)
            &#123;
                if (array[i].pos &lt; array[j].pos)
                &#123;
                    result.push_back(array[i].pos + 1);
                    result.push_back(array[j].pos + 1);
                &#125; else
                &#123;
                    result.push_back(array[j].pos + 1);
                    result.push_back(array[i].pos + 1);
                &#125;
                break;
            &#125; else if (sum &lt; target)
            &#123;
                i++;
            &#125; else if (sum &gt; target)
            &#123;
                j--;
            &#125;
        &#125;
        return result;
    &#125;
&#125;;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="Analysis"><a href="#Analysis" class="headerlink" title="Analysis"></a>Analysis</h3><p>sort the array, then test from head and end, until catch the right answer</p>
]]></content>
      <categories>
        <category>leetcode</category>
      </categories>
      <tags>
        <tag>leetcode</tag>
        <tag>c++</tag>
      </tags>
  </entry>
  <entry>
    <title>ambari-summary</title>
    <url>/2017/05/09/ambari-summary/</url>
    <content><![CDATA[<h2 id="初识ambari"><a href="#初识ambari" class="headerlink" title="初识ambari"></a>初识ambari</h2><p><a href="http://ambari.apache.org/">ambari</a>是一个大数据平台的管理工具，包含了<code>hadoop</code>, <code>yarn</code>, <code>hive</code>, <code>hbase</code>, <code>spark</code>等大数据的基础架构和工具，简化了数据平台的搭建，之前只是在同事搭建好平台后的一些使用，这次有机会从头开始用<code>ambari</code>来搭建一个测试的数据平台，过程中也踩到不少坑，简单记录下。</p>
<h2 id="简单过程"><a href="#简单过程" class="headerlink" title="简单过程"></a>简单过程</h2><ul>
<li>第一个坑<br>在刚开始是按照官网的指南，用maven构建，因为GFW的原因，导致反复失败等待，也就是这个<a href="https://cwiki.apache.org/confluence/display/AMBARI/Installation+Guide+for+Ambari+2.5.0">guide</a>，因为对maven不熟悉导致有些按图索骥，浪费了很多时间，之后才知道可以直接加repo用yum安装，然而用yum安装马上就出现了第二个坑。</li>
<li>第二个坑<br>因为在线的repo还是因为网络原因很慢很慢，用proxychains勉强把ambari-server本身安装好了，<a href="http://public-repo-1.hortonworks.com/ambari/centos7/2.x/updates/2.5.0.3/ambari.repo">ambari.repo</a>将这个放进<code>/etc/yum.repos.d/</code>路径下，然后<code>yum update &amp;&amp; yum install ambari-server</code>安装即可，如果有条件就用proxychains走下代理。</li>
<li>第三步<br>安装好ambari-server后先执行<code>ambari-server setup</code>做一些初始化设置，其中包含了JDK路径的设置，数据库设置，设置好就OK了，然后执行<code>ambari-server start</code>启动服务，这里有个小插曲，因为<code>ambari-server</code>涉及到这么多服务，所以管理控制监控之类的模块是必不可少的，这部分可以在<code>ambari-server</code>的web ui界面安装，也可以命令行提前安装，这部分被称为<code>HDF Management Pack</code>，运行```ambari-server install-mpack \</li>
<li>-mpack=<a href="http://public-repo-1.hortonworks.com/HDF/centos7/2.x/updates/2.1.4.0/tars/hdf_ambari_mp/hdf-ambari-mpack-2.1.4.0-5.tar.gz">http://public-repo-1.hortonworks.com/HDF/centos7/2.x/updates/2.1.4.0/tars/hdf_ambari_mp/hdf-ambari-mpack-2.1.4.0-5.tar.gz</a> \</li>
<li>-purge \</li>
<li>-verbose```<br>安装，当然这个压缩包可以下载之后指到本地路径安装，然后就可以重启<code>ambari-server</code></li>
</ul>
]]></content>
      <categories>
        <category>data analysis</category>
      </categories>
      <tags>
        <tag>hadoop</tag>
        <tag>cluster</tag>
      </tags>
  </entry>
  <entry>
    <title>binary-watch</title>
    <url>/2016/09/29/binary-watch/</url>
    <content><![CDATA[<h3 id="problem"><a href="#problem" class="headerlink" title="problem"></a>problem</h3><p>A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59).  </p>
<p>Each LED represents a zero or one, with the least significant bit on the right.  </p>
<p><img data-src="http://7sbp1g.com1.z0.glb.clouddn.com/Binary_clock_samui_moon.jpg?imageView2/2/w/620"></p>
<p>For example, the above binary watch reads “3:25”.  </p>
<p>Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent.  </p>
<h4 id="Example"><a href="#Example" class="headerlink" title="Example:"></a>Example:</h4><pre class="line-numbers language-none"><code class="language-none">Input: n &#x3D; 1
Return: [&quot;1:00&quot;, &quot;2:00&quot;, &quot;4:00&quot;, &quot;8:00&quot;, &quot;0:01&quot;, &quot;0:02&quot;, &quot;0:04&quot;, &quot;0:08&quot;, &quot;0:16&quot;, &quot;0:32&quot;]<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<h4 id="Note"><a href="#Note" class="headerlink" title="Note:"></a>Note:</h4><ul>
<li>The order of output does not matter.</li>
<li>The hour must not contain a leading zero, for example “01:00” is not valid, it should be “1:00”.</li>
<li>The minute must be consist of two digits and may contain a leading zero, for example “10:2” is not valid, it should be “10:02”.</li>
</ul>
<h3 id="题解"><a href="#题解" class="headerlink" title="题解"></a>题解</h3><p>又是参（chao）考（xi）别人的代码，嗯，就是这么不要脸，<a href="http://www.cnblogs.com/grandyang/p/5896454.html">链接</a></p>
<h4 id="Code"><a href="#Code" class="headerlink" title="Code"></a>Code</h4><pre class="line-numbers language-C++" data-language="C++"><code class="language-C++">class Solution &#123;
public:
    vector&lt;string&gt; readBinaryWatch(int num) &#123;
        vector&lt;string&gt; res;
        for (int h &#x3D; 0; h &lt; 12; ++h) &#123;
            for (int m &#x3D; 0; m &lt; 60; ++m) &#123;
                if (bitset&lt;10&gt;((h &lt;&lt; 6) + m).count() &#x3D;&#x3D; num) &#123;
                    res.push_back(to_string(h) + (m &lt; 10 ? &quot;:0&quot; : &quot;:&quot;) + to_string(m));
                &#125;
            &#125;
        &#125;
        return res;
    &#125;
&#125;;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>]]></content>
      <categories>
        <category>leetcode</category>
      </categories>
      <tags>
        <tag>leetcode</tag>
        <tag>c++</tag>
      </tags>
  </entry>
  <entry>
    <title>docker-mysql-cluster</title>
    <url>/2016/08/14/docker-mysql-cluster/</url>
    <content><![CDATA[<h3 id="docker-mysql-cluster"><a href="#docker-mysql-cluster" class="headerlink" title="docker-mysql-cluster"></a>docker-mysql-cluster</h3><p>基于docker搭了个mysql集群，稍微记一下，<br>首先是新建mysql主库容<br>  <span id="more"></span><br><code>docker run -d -e MYSQL_ROOT_PASSWORD=admin --name mysql-master -p 3307:3306 mysql:latest</code><br><code>-d</code>表示容器运行在后台，<code>-e</code>表示设置环境变量，即<code>MYSQL_ROOT_PASSWORD=admin</code>,设置了mysql的root密码，<br><code>--name</code>表示容器名，<code>-p</code>表示端口映射，将内部mysql:3306映射为外部的3307，最后的<code>mysql:latest</code>表示镜像名<br>此外还可以用<code>-v /local_path/my-master.cnf:/etc/mysql/my.cnf</code>来映射配置文件<br>然后同理启动从库<br><code>docker run -d -e MYSQL_ROOT_PASSWORD=admin --name mysql-slave -p 3308:3306 mysql:latest</code><br>然后进入主库改下配置文件<br><code>docker-enter mysql-master</code>如果无法进入就用<code>docker ps -a</code>看下容器是否在正常运行，如果status显示<br>未正常运行，则用<code>docker logs mysql-master</code>看下日志哪里出错了。<br>进入容器后，我这边使用的镜像的mysqld配置文件是在<code>/etc/mysql</code>下面，这个最新版本的mysql的配置文件包含<br>三部分，<code>/etc/mysql/my.cnf</code>和<code>/etc/mysql/conf.d/mysql.cnf</code>，还有<code>/etc/mysql/mysql.conf.d/mysqld.cnf</code><br>这里需要改的是最后一个，加上</p>
<pre class="line-numbers language-none"><code class="language-none">log-bin &#x3D; mysql-bin
server_id &#x3D; 1<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>保存后退出容器重启主库容器，然后进入从库更改相同文件，</p>
<pre class="line-numbers language-none"><code class="language-none">log-bin &#x3D; mysql-bin
server_id &#x3D; 2<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<h3 id="主从配置"><a href="#主从配置" class="headerlink" title="主从配置"></a>主从配置</h3><p>同样退出重启容器，然后是配置主从，首先进入主库，用命令mysql -u root -pxxxx进入mysql，然后赋予一个同步<br>权限<code>GRANT REPLICATION SLAVE ON *.* to &#39;backup&#39;@&#39;%&#39; identified by &#39;123456&#39;;</code>还是同样说明下，ON *.*表示了数<br>据库全部的权限，如果要指定数据库/表的话可以使用类似<code>testDb/testTable</code>，然后是<code>&#39;backup&#39;@&#39;%&#39;</code>表示给予同步<br>权限的用户名及其主机ip，%表示不限制ip，当然如果有防火墙的话还是会有限制的，最后的<code>identified by &#39;123456&#39;</code><br>表示同步用户的密码，然后就查看下主库的状态信息<code>show master status</code>，如下图：<br><img data-src="https://ooo.0o0.ooo/2016/08/10/57aac43029559.png" alt="9G5FE[9%@7%G(B`Q7]E)5@R.png"><br>把file跟position记下来，然后再开一个terminal，进入从库容器，登陆mysql，然后设置主库</p>
<pre class="line-numbers language-none"><code class="language-none">change master to
master_host&#x3D;&#39;xxx.xxx.xxx.xxx&#39;,   &#x2F;&#x2F;如果主从库的容器都在同一个宿主机上，这里的ip是docker容器的ip
master_user&#x3D;&#39;backup&#39;,            &#x2F;&#x2F;就是上面的赋予权限的用户
master_password&#x3D;&#39;123456&#39;,
master_log_file&#x3D;&#39;mysql-bin.000004&#39;,  &#x2F;&#x2F;主库中查看到的file
master_log_pos&#x3D;312,                  &#x2F;&#x2F;主库中查看到的position
master_port&#x3D;3306;                    &#x2F;&#x2F;如果是同一宿主机，这里使用真实的3306端口，3308及主库的3307是给外部连接使用的<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>通过<code>docker-ip mysql-master</code>可以查看容器的ip<br><img data-src="https://ooo.0o0.ooo/2016/08/10/57aac63fd02f1.png" alt="S(GP)P(M$N3~N1764@OW3E0.png"><br>这里有一点是要注意的，也是我踩的坑，就是如果是同一宿主机下两个mysql容器互联，我这里只能通过docker-ip和真实<br>的3306端口能够连接成功。<br>本文参考了<a href="http://blog.csdn.net/qq362228416/article/details/48569293">这位同学的文章</a></p>
]]></content>
      <categories>
        <category>docker</category>
      </categories>
      <tags>
        <tag>docker</tag>
        <tag>mysql</tag>
      </tags>
  </entry>
  <entry>
    <title>docker比一般多一点的初学者介绍</title>
    <url>/2020/03/08/docker%E6%AF%94%E4%B8%80%E8%88%AC%E5%A4%9A%E4%B8%80%E7%82%B9%E7%9A%84%E5%88%9D%E5%AD%A6%E8%80%85%E4%BB%8B%E7%BB%8D/</url>
    <content><![CDATA[<p>因为最近想搭一个phabricator用来做看板和任务管理，一开始了解这个是Easy大大有在微博推荐过，后来苏洋也在群里和博客里说到了，看上去还不错的样子，因为主角是docker所以就不介绍太多，后面有机会写一下。</p>
<p>docker最开始是之前在某位大佬的博客看到的，看上去有点神奇，感觉是一种轻量级的虚拟机，但是能做的事情好像差不多，那时候是在Ubuntu系统的vps里起一个Ubuntu的docker，然后在里面装个nginx，配置端口映射就可以访问了，后来也草草写过一篇使用docker搭建mysql集群，但是最近看了下好像是因为装docker的大佬做了一些别名还是什么操作，导致里面用的操作都不具有普遍性，而且主要是把搭的过程写了下，属于囫囵吞枣，没理解docker是干啥的，为啥用docker，就是操作了下，这几天借着搭phabricator的过程，把一些原来不理解，或者原来理解错误的地方重新理一下。</p>
<p>之前写的 mysql 集群，一主二备，这种架构在很多小型应用里都是这么配置的，而且一般是直接在三台 vps 里启动三个 mysql 实例，但是如果换成 docker 会有什么好处呢，其实就是方便部署，比如其中一台备库挂了，我要加一台，或者说备库的 qps 太高了，需要再加一个，如果要在 vps 上搭建的话，首先要买一台机器，等初始化，然后在上面修改源，更新，装 mysql ，然后配置主从，可能还要处理防火墙等等，如果把这些打包成一个 docker 镜像，并且放在自己的 docker registry，那就直接run 一下就可以了；还有比如在公司要给一个新同学整一套开发测试环境，以 Java 开发为例，要装 git，maven，jdk，配置 maven settings 和各种 rc，整合在一个镜像里的话，就会很方便了；再比如微服务的水平扩展。</p>
<p>但是为啥 docker 会有这种优势，听起来好像虚拟机也可以干这个事，但是虚拟机动辄上 G，而且需要 VMware，virtual box 等支持，不适合在Linux服务器环境使用，而且占用资源也会非常大。说得这么好，那么 docker 是啥呢</p>
<p>docker 主要使用 Linux 中已经存在的两种技术的一个整合升级，一个是 namespace，一个是cgroups，相比于虚拟机需要完整虚拟出一个操作系统运行基础，docker 基于宿主机内核，通过 namespace 和 cgroups 分隔进程，理念就是提供一个隔离的最小化运行依赖，这样子相对于虚拟机就有了巨大的便利性，具体的 namespace 和 cgroups 就先不展开讲，可以参考耗子叔的文章</p>
<h2 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h2><p>那么我们先安装下 docker，参考官方的教程，<a href="https://docs.docker.com/install/linux/docker-ce/ubuntu/">安装</a>，我的系统是 ubuntu 的，就贴了 ubuntu 的链接，用其他系统的可以找到对应的系统文档安装，安装完了的话看看 docker 的信息</p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell">sudo docker info<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>输出以下信息<br><img data-src="https://i.loli.net/2020/03/08/IJP157hLqlgo4Ow.png"></p>
<h2 id="简单运行"><a href="#简单运行" class="headerlink" title="简单运行"></a>简单运行</h2><p>然后再来运行个 hello world 呗，</p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell">sudo docker run hello-world<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>输出了这些<br><img data-src="https://i.loli.net/2020/03/08/7dO2JWbf3wVLPsN.png"></p>
<p>看看这个运行命令是怎么用的，一般都会看到这样子的，sudo docker run -it ubuntu bash<code>, 前面的 docker run 反正就是运行一个容器的意思，</code>-it<code>是啥呢，还有这个什么 ubuntu bash，来看看</code>docker run`的命令帮助信息</p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell">-i, --interactive                    Keep STDIN open even if not attached<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>就是要有输入，我们运行的时候能输入</p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell">-t, --tty                            Allocate a pseudo-TTY<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>要有个虚拟终端，</p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell">Usage:	docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

Run a command in a new container<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<h2 id="镜像"><a href="#镜像" class="headerlink" title="镜像"></a>镜像</h2><p>上面说的-it 就是这里的 options，后面那个 ubuntu 就是 image 辣，image 是啥呢</p>
<p><strong>Docker 把应用程序及其依赖，打包在 image 文件里面</strong>，可以把它理解成为类似于虚拟机的镜像或者运行一个进程的代码，跑起来了的叫docker 容器或者进程，比如我们将要运行的<code>docker run -it ubuntu bash</code>的ubuntu 就是个 ubuntu 容器的镜像，将这个镜像运行起来后，我们可以进入容器像使用 ubuntu 一样使用它，来看下我们的镜像，使用<code>sudo docker image ls</code>就能列出我们宿主机上的 docker 镜像了</p>
<p><img data-src="https://i.loli.net/2020/03/08/G3ltzyVLqheDRgo.png"></p>
<p>一个 ubuntu 镜像才 64MB，非常小巧，然后是后面的<code>bash</code>，我通过交互式启动了一个 ubuntu 容器，然后在这个启动的容器里运行了 bash 命令，这样就可以在容器里玩一下了</p>
<h2 id="在容器里看下进程，"><a href="#在容器里看下进程，" class="headerlink" title="在容器里看下进程，"></a>在容器里看下进程，</h2><p><img data-src="https://i.loli.net/2020/03/08/2qQFPbxB9uEzcrJ.png"></p>
<p>只有刚才运行容器的 bash 进程和我刚执行的 ps，这里有个可以注意下的，bash 这个进程的 pid 是 1，其实这里就用到了 linux 中的PID Namespace，容器会隔离出一个 pid 的名字空间，这里面的进程跟外部的 pid 命名独立</p>
<h2 id="查看宿主机上的容器"><a href="#查看宿主机上的容器" class="headerlink" title="查看宿主机上的容器"></a>查看宿主机上的容器</h2><pre class="line-numbers language-shell" data-language="shell"><code class="language-shell">sudo docker ps -a<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p><img data-src="https://i.loli.net/2020/03/08/spGtzcDXKv3ORU7.png"></p>
<h2 id="如何进入一个正在运行中的-docker-容器"><a href="#如何进入一个正在运行中的-docker-容器" class="headerlink" title="如何进入一个正在运行中的 docker 容器"></a>如何进入一个正在运行中的 docker 容器</h2><p>这个应该是比较常用的，因为比如是一个微服务容器，有时候就像看下运行状态，日志啥的</p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell">sudo docker exec -it [containerID] bash<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p><img data-src="https://i.loli.net/2020/03/08/uswmh3Izp65kc9n.png"></p>
<h2 id="查看日志"><a href="#查看日志" class="headerlink" title="查看日志"></a>查看日志</h2><pre class="line-numbers language-shell" data-language="shell"><code class="language-shell">sudo docker logs [containerID]<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>我在运行容器的终端里胡乱输入点啥，然后通过上面的命令就可以看到啦</p>
<p><img data-src="https://i.loli.net/2020/03/08/RJAvlhEMD7VfbXz.png"></p>
<p><img data-src="https://i.loli.net/2020/03/08/L4YRni95lBzEmFh.png"></p>
]]></content>
      <categories>
        <category>Docker</category>
        <category>介绍</category>
      </categories>
      <tags>
        <tag>Docker</tag>
        <tag>namespace</tag>
        <tag>cgroup</tag>
      </tags>
  </entry>
  <entry>
    <title>docker比一般多一点的初学者介绍三</title>
    <url>/2020/03/21/docker%E6%AF%94%E4%B8%80%E8%88%AC%E5%A4%9A%E4%B8%80%E7%82%B9%E7%9A%84%E5%88%9D%E5%AD%A6%E8%80%85%E4%BB%8B%E7%BB%8D%E4%B8%89/</url>
    <content><![CDATA[<h2 id="运行第一个-Dockerfile"><a href="#运行第一个-Dockerfile" class="headerlink" title="运行第一个 Dockerfile"></a>运行第一个 Dockerfile</h2><p>上一篇的 Dockerfile 我们停留在构建阶段，现在来把它跑起来</p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell">docker run -d -p 80 --name static_web nicksxs&#x2F;static_web \
nginx -g &quot;daemon off;&quot;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>这里的<code>-d</code>表示以分离模型运行docker (detached),然后-p 是表示将容器的 80 端口开放给宿主机，然后容器名就叫 static_web,使用了我们上次构建的 static_web 镜像，后面的是让 nginx 在前台运行<br><img data-src="https://i.loli.net/2020/03/21/VCEuf5BTopXNkcA.png"><br>可以看到返回了个容器 id，但是具体情况没出现，也没连上去，那我们想看看怎么访问在 Dockerfile 里写的静态页面，我们来看下docker 进程<br><img data-src="https://i.loli.net/2020/03/21/Cx1JYGBrHRqojpz.png"><br>发现为我们随机分配了一个宿主机的端口，32768，去服务器的防火墙把这个外网端口开一下，看看是不是符合我们的预期呢<br><img data-src="https://i.loli.net/2020/03/21/xhAcQlX5iP9KnYB.png"><br>好像不太对额，应该是 ubuntu 安装的 nginx 的默认工作目录不对，我们来进容器看看，再熟悉下命令<code>docker exec -it 4792455ca2ed /bin/bash</code><br>记得容器 id 换成自己的，进入容器后得找找 nginx 的配置文件，通常在<code>/etc/nginx</code>,<code>/usr/local/etc</code>等目录下，然后找到我们的目录是在这<br><img data-src="https://i.loli.net/2020/03/21/wE8TfkbC2d9pNuv.png"><br>所以把刚才的内容复制过去再试试<br><img data-src="https://i.loli.net/2020/03/21/qNkpHn3GW8aiwIr.png"><br>目标达成，give me five✌️</p>
<h2 id="第二个-Dockerfile"><a href="#第二个-Dockerfile" class="headerlink" title="第二个 Dockerfile"></a>第二个 Dockerfile</h2><p>然后就想来动态一点的，毕竟写过 PHP，就来试试 PHP<br>再建一个目录叫 dynamic_web，里面创建 src 目录，放一个 index.php<br>内容是</p>
<pre class="line-numbers language-php" data-language="php"><code class="language-php"><span class="token php language-php"><span class="token delimiter important">&lt;?php</span>
<span class="token keyword">echo</span> <span class="token string double-quoted-string">"Hello World!"</span><span class="token punctuation">;</span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>然后在 dynamic_web 目录下创建 Dockerfile，</p>
<pre class="line-numbers language-Dockerfile" data-language="Dockerfile"><code class="language-Dockerfile">FROM trafex&#x2F;alpine-nginx-php7:latest
COPY src&#x2F; &#x2F;var&#x2F;www&#x2F;html
EXPOSE 80<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>Dockerfile 虽然只有三行，不过要着重说明下，这个底包其实不是docker 官方的，有两点考虑，一点是官方的基本都是 php apache 的镜像，还有就是 alpine这个，截取一段中文介绍</p>
<blockquote>
<p>Alpine 操作系统是一个面向安全的轻型 Linux 发行版。它不同于通常 Linux 发行版，Alpine 采用了 musl libc 和 busybox 以减小系统的体积和运行时资源消耗，但功能上比 busybox 又完善的多，因此得到开源社区越来越多的青睐。在保持瘦身的同时，Alpine 还提供了自己的包管理工具 apk，可以通过 <a href="https://pkgs.alpinelinux.org/packages">https://pkgs.alpinelinux.org/packages</a> 网站上查询包信息，也可以直接通过 apk 命令直接查询和安装各种软件。<br>Alpine 由非商业组织维护的，支持广泛场景的 Linux发行版，它特别为资深/重度Linux用户而优化，关注安全，性能和资源效能。Alpine 镜像可以适用于更多常用场景，并且是一个优秀的可以适用于生产的基础系统/环境。</p>
</blockquote>
<blockquote>
<p>Alpine Docker 镜像也继承了 Alpine Linux 发行版的这些优势。相比于其他 Docker 镜像，它的容量非常小，仅仅只有 5 MB 左右（对比 Ubuntu 系列镜像接近 200 MB），且拥有非常友好的包管理机制。官方镜像来自 docker-alpine 项目。</p>
</blockquote>
<blockquote>
<p>目前 Docker 官方已开始推荐使用 Alpine 替代之前的 Ubuntu 做为基础镜像环境。这样会带来多个好处。包括镜像下载速度加快，镜像安全性提高，主机之间的切换更方便，占用更少磁盘空间等。  </p>
</blockquote>
<p>一方面在没有镜像的情况下，拉取 docker 镜像还是比较费力的，第二个就是也能节省硬盘空间，所以目前有大部分的 docker 镜像都将 alpine 作为基础镜像了<br>然后再来构建下<br><img data-src="https://i.loli.net/2020/03/21/56cuKf1ObvkBSG3.png"><br>这里还有个点，就是上面的那个镜像我们也是 EXPOSE 80端口，然后外部宿主机会随机映射一个端口，为了偷个懒，我们就直接指定外部端口了<br><code>docker run -d -p 80:80 dynamic_web</code>打开浏览器发现访问不了，咋回事呢<br>因为我们没看<code>trafex/alpine-nginx-php7:latest</code>这个镜像<a href="https://hub.docker.com/r/trafex/alpine-nginx-php7">说明</a>,它内部的服务是 8080 端口的，所以我们映射的暴露端口应该是 8080，再用<code> docker run -d -p 80:8080 dynamic_web</code>这个启动，<br><img data-src="https://i.loli.net/2020/03/21/qDd2LVhz1Po4McX.png"></p>
]]></content>
      <categories>
        <category>Docker</category>
        <category>介绍</category>
      </categories>
      <tags>
        <tag>Docker</tag>
        <tag>namespace</tag>
        <tag>Dockerfile</tag>
      </tags>
  </entry>
  <entry>
    <title>docker比一般多一点的初学者介绍二</title>
    <url>/2020/03/15/docker%E6%AF%94%E4%B8%80%E8%88%AC%E5%A4%9A%E4%B8%80%E7%82%B9%E7%9A%84%E5%88%9D%E5%AD%A6%E8%80%85%E4%BB%8B%E7%BB%8D%E4%BA%8C/</url>
    <content><![CDATA[<h2 id="限制下-docker-的-cpu-使用率"><a href="#限制下-docker-的-cpu-使用率" class="headerlink" title="限制下 docker 的 cpu 使用率"></a>限制下 docker 的 cpu 使用率</h2><p>这里我们开始玩一点有意思的，我们在容器里装下 vim 和 gcc，然后写这样一段 c 代码</p>
<pre class="line-numbers language-C" data-language="C"><code class="language-C">#include &lt;stdio.h&gt;
int main(void)
&#123;
    int i &#x3D; 0;
    for(;;) i++;
    return 0;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>就是一个最简单的死循环，然后在容器里跑起来</p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell">$ gcc 1.c 
$ .&#x2F;a.out<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>然后我们来看下系统资源占用（CPU）<br><img data-src="https://i.loli.net/2020/03/09/Xs562iawhHyMxeO.png" alt="Xs562iawhHyMxeO"><br>上图是在容器里的，可以看到 cpu 已经 100%了<br>然后看看容器外面的<br><img data-src="https://i.loli.net/2020/03/09/ecqH8XJ4k7rKhzu.png" alt="ecqH8XJ4k7rKhzu"><br>可以看到一个核的 cpu 也被占满了，因为是个双核的机器，并且代码是单线程的<br>然后呢我们要做点啥<br>因为已经在这个 ubuntu 容器中装了 vim 和 gcc，考虑到国内的网络，所以我们先把这个容器 commit 一下，</p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell">docker commit -a &quot;nick&quot; -m &quot;my ubuntu&quot; f63c5607df06 my_ubuntu:v1<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>然后再运行起来</p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell">docker run -it --cpus&#x3D;0.1 my_ubuntu:v1 bash<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p><img data-src="https://i.loli.net/2020/03/15/x2oGCPQr9Mm8ZYj.png"><br>我们的代码跟可执行文件都还在，要的就是这个效果，然后再运行一下<br><img data-src="https://i.loli.net/2020/03/10/3EgzYxpqlwobNRj.png"><br>结果是这个样子的，有点神奇是不，关键就在于 run 的时候的<code>--cpus=0.1</code>这个参数，它其实就是基于我前一篇说的 cgroup 技术，能将进程之间的cpu，内存等资源进行隔离</p>
<h2 id="开始第一个-Dockerfile"><a href="#开始第一个-Dockerfile" class="headerlink" title="开始第一个 Dockerfile"></a>开始第一个 Dockerfile</h2><p>上一面为了复用那个我装了 vim 跟 gcc 的容器，我把它提交到了本地，使用了<code>docker commit</code>命令，有点类似于 git 的 commit，但是这个不是个很好的操作方式，需要手动介入，这里更推荐使用 Dockerfile 来构建镜像</p>
<pre class="line-numbers language-Docker" data-language="Docker"><code class="language-Docker">From ubuntu:latest
MAINTAINER Nicksxs &quot;nicksxs@hotmail.com&quot;
RUN  sed -i s@&#x2F;archive.ubuntu.com&#x2F;@&#x2F;mirrors.aliyun.com&#x2F;@g &#x2F;etc&#x2F;apt&#x2F;sources.list
RUN apt-get clean
RUN apt-get update &amp;&amp; apt install -y nginx
RUN echo &#39;Hi, i am in container&#39; \
    &gt; &#x2F;usr&#x2F;share&#x2F;nginx&#x2F;html&#x2F;index.html
EXPOSE 80<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>先解释下这是在干嘛，首先是这个<code>From ubuntu:latest</code>基于的 ubuntu 的最新版本的镜像，然后第二行是维护人的信息，第三四行么作为墙内人你懂的，把 ubuntu 的源换成阿里云的，不然就有的等了，然后就是装下 nginx，往默认的 nginx 的入口 html 文件里输入一行欢迎语，然后暴露 80 端口<br>然后我们使用<code>sudo docker build -t=&quot;nicksxs/static_web&quot; .</code>命令来基于这个 Dockerfile 构建我们自己的镜像，过程中是这样的<br><img data-src="https://i.loli.net/2020/03/15/aiIMrhy9WHetDSl.png"><br><img data-src="https://i.loli.net/2020/03/11/RC6yjImFZps4HWl.png"><br>可以看到图中，我的 Dockerfile 是 7 行，里面就执行了 7 步，并且每一步都有一个类似于容器 id 的层 id 出来，这里就是一个比较重要的东西，docker 在构建的时候其实是有这个层的概念，Dockerfile 里的每一行都会往上加一层，这里有还注意下命令后面的<code>.</code>，代表当前目录下会自行去寻找 Dockerfile 进行构建，构建完了之后我们再看下我们的本地镜像<br><img data-src="https://i.loli.net/2020/03/11/op5c7UGTbhjwPOI.png"><br>我们自己的镜像出现啦<br>然后有个问题，如果这个构建中途报了错咋办呢，来试试看，我们把 nginx 改成随便的一个错误名，nginxx(不知道会不会运气好真的有这玩意)，再来 build 一把<br><img data-src="https://i.loli.net/2020/03/14/ALWIobjchnu1Rvi.png"><br>找不到 nginxx 包，是不是这个镜像就完全不能用呢，当然也不是，因为前面说到了，docker 是基于层去构建的，可以看到前面的 4 个 step 都没报错，那我们基于最后的成功步骤创建下容器看看<br>也就是<code>sudo docker run -t -i bd26f991b6c8 /bin/bash</code><br>答案是可以的，只是没装成功 nginx<br><img data-src="https://i.loli.net/2020/03/14/grcMNVxTabDPipu.png"><br>还有一点注意到没，前面的几个 step 都有一句 <code>Using cache</code>，说明 docker 在构建镜像的时候是有缓存的，这也更能说明 docker 是基于层去构建镜像，同样的底包，同样的步骤，这些层是可以被复用的，这就是 docker 的构建缓存，当然我们也可以在 build 的时候加上<code>--no-cache</code>去把构建缓存禁用掉。</p>
]]></content>
      <categories>
        <category>Docker</category>
        <category>介绍</category>
      </categories>
      <tags>
        <tag>Docker</tag>
        <tag>namespace</tag>
        <tag>cgroup</tag>
      </tags>
  </entry>
  <entry>
    <title>docker使用中发现的echo命令的一个小技巧及其他</title>
    <url>/2020/03/29/echo%E5%91%BD%E4%BB%A4%E7%9A%84%E4%B8%80%E4%B8%AA%E5%B0%8F%E6%8A%80%E5%B7%A7/</url>
    <content><![CDATA[<p>最近做 docker 系列，会经常进到 docker 内部，如上一篇介绍的，这些镜像一般都有用 ubuntu 或者alpine 这样的 Linux 系统作为底包，如果构建镜像的时候没有替换源的话，因为你懂的原因，在内部想编辑下东西要安装 vim 就会很慢很慢，thousand years later~<br>而且如果在容器内部想改源配置的话也要编辑器，就陷入了一个鸡生蛋，跟蛋生鸡的问题中，对于 linux 大神来说应该有一万种方法解决这个问题，对于我这个渣渣来说可能只想到了这个土方法，先 cp backup 一下 sources.list, 再 echo “xxx” &gt; sources.list, 这里就碰到了一个问题，这个 sources.list 一般不止一行，直接 echo 的话就解析不了了，不过 echo 可以支持”\n”转义，就是加-e<br>看一下解释和示例<br><img data-src="https://i.loli.net/2020/03/23/4vlxSOuR2DdF5kp.png"><br>还有一点也是在这个时候要安装 vim 之类的，得知道是什么镜像底包，如果是用 uname 指令，其实看到的是宿主机的系统，得用<code>cat /etc/issue</code><br><img data-src="https://i.loli.net/2020/03/29/mh5YxdDnX3VSkg8.png"><br>这里稍稍记一下</p>
]]></content>
      <categories>
        <category>Linux</category>
        <category>Docker</category>
        <category>命令</category>
        <category>echo</category>
        <category>发行版本</category>
      </categories>
      <tags>
        <tag>linux</tag>
        <tag>Docker</tag>
        <tag>echo</tag>
        <tag>uname</tag>
        <tag>发行版</tag>
      </tags>
  </entry>
  <entry>
    <title>gogs使用webhook部署react单页应用</title>
    <url>/2020/02/22/gogs%E4%BD%BF%E7%94%A8webhook%E9%83%A8%E7%BD%B2react%E5%8D%95%E9%A1%B5%E5%BA%94%E7%94%A8/</url>
    <content><![CDATA[<p>众所周知，我是个前端彩笔，但是也想做点自己可以用的工具页面，所以就让朋友推荐了蚂蚁出品的 ant design，说基本可以直接 ctrl-c ctrl-v，实测对我这种来说还是有点难的，不过也能写点，但是现在碰到的问题是怎么部署到自己的服务器上去<br>用 ant design 写的是个单页应用，实际来说就是一个 html 加 css 跟 js，最初的时候是直接 build 完就 scp 上去，也考虑过 rsync 之类的，但是都感觉不够自动化，正好自己还没这方面的经验就想折腾下，因为我自己搭的仓库应用是 gogs，搜了一下主要是跟 drones 配合做 ci/cd，研究了一下发现其实这个事情没必要这么搞(PS：drone 也不好用)，整个 hook 就可以了, 但是实际上呢，这东西也不是那么简单<br>首先是需要在服务器上装 <a href="https://github.com/adnanh/webhook">webhook</a>，这个我一开始用 snap 安装，但是出现问题，run 的时候会出现后面参数带的 hooks.json 文件找不到，然后索性就直接 github 上下最新版，放 /usr/local/bin 了，webhook 的原理呢其实也比较简单，就是起一个 http 服务，通过 post 请求调用，解析下参数，如果跟配置的参数一致，就调用对应的命令或者脚本。</p>
<h2 id="配置-hooks-json"><a href="#配置-hooks-json" class="headerlink" title="配置 hooks.json"></a>配置 hooks.json</h2><p>webhook 的配置，需要的两个文件，一个是 hooks.json，这个是 webhook 服务的配置文件，像这样</p>
<pre class="line-numbers language-json" data-language="json"><code class="language-json"><span class="token punctuation">[</span>
  <span class="token punctuation">&#123;</span>
    <span class="token property">"id"</span><span class="token operator">:</span> <span class="token string">"redeploy-app"</span><span class="token punctuation">,</span>
    <span class="token property">"execute-command"</span><span class="token operator">:</span> <span class="token string">"/opt/scripts/redeploy.sh"</span><span class="token punctuation">,</span>
    <span class="token property">"command-working-directory"</span><span class="token operator">:</span> <span class="token string">"/opt/scripts"</span><span class="token punctuation">,</span>
    <span class="token property">"pass-arguments-to-command"</span><span class="token operator">:</span>
    <span class="token punctuation">[</span>
      <span class="token punctuation">&#123;</span>
        <span class="token property">"source"</span><span class="token operator">:</span> <span class="token string">"payload"</span><span class="token punctuation">,</span>
        <span class="token property">"name"</span><span class="token operator">:</span> <span class="token string">"head_commit.message"</span>
      <span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
      <span class="token punctuation">&#123;</span>
        <span class="token property">"source"</span><span class="token operator">:</span> <span class="token string">"payload"</span><span class="token punctuation">,</span>
        <span class="token property">"name"</span><span class="token operator">:</span> <span class="token string">"pusher.name"</span>
      <span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
      <span class="token punctuation">&#123;</span>
        <span class="token property">"source"</span><span class="token operator">:</span> <span class="token string">"payload"</span><span class="token punctuation">,</span>
        <span class="token property">"name"</span><span class="token operator">:</span> <span class="token string">"head_commit.id"</span>
      <span class="token punctuation">&#125;</span>
    <span class="token punctuation">]</span><span class="token punctuation">,</span>
    <span class="token property">"trigger-rule"</span><span class="token operator">:</span>
    <span class="token punctuation">&#123;</span>
      <span class="token property">"and"</span><span class="token operator">:</span>
      <span class="token punctuation">[</span>
        <span class="token punctuation">&#123;</span>
          <span class="token property">"match"</span><span class="token operator">:</span>
          <span class="token punctuation">&#123;</span>
            <span class="token property">"type"</span><span class="token operator">:</span> <span class="token string">"payload-hash-sha1"</span><span class="token punctuation">,</span>
            <span class="token property">"secret"</span><span class="token operator">:</span> <span class="token string">"your-github-secret"</span><span class="token punctuation">,</span>
            <span class="token property">"parameter"</span><span class="token operator">:</span>
            <span class="token punctuation">&#123;</span>
              <span class="token property">"source"</span><span class="token operator">:</span> <span class="token string">"header"</span><span class="token punctuation">,</span>
              <span class="token property">"name"</span><span class="token operator">:</span> <span class="token string">"X-Hub-Signature"</span>
            <span class="token punctuation">&#125;</span>
          <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
        <span class="token punctuation">&#123;</span>
          <span class="token property">"match"</span><span class="token operator">:</span>
          <span class="token punctuation">&#123;</span>
            <span class="token property">"type"</span><span class="token operator">:</span> <span class="token string">"value"</span><span class="token punctuation">,</span>
            <span class="token property">"value"</span><span class="token operator">:</span> <span class="token string">"refs/heads/master"</span><span class="token punctuation">,</span>
            <span class="token property">"parameter"</span><span class="token operator">:</span>
            <span class="token punctuation">&#123;</span>
              <span class="token property">"source"</span><span class="token operator">:</span> <span class="token string">"payload"</span><span class="token punctuation">,</span>
              <span class="token property">"name"</span><span class="token operator">:</span> <span class="token string">"ref"</span>
            <span class="token punctuation">&#125;</span>
          <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
      <span class="token punctuation">]</span>
    <span class="token punctuation">&#125;</span>
  <span class="token punctuation">&#125;</span>
<span class="token punctuation">]</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>这是个跟 github搭配的示例，首先 id 表示的是这个对应 hook 的识别 id，也可以看到这个 hooks.json 的结构是这样的一个数组，然后就是要执行的命令和命令执行的参数，值得注意的是这个<code>trigger-rule</code>,就是请求进来了回去匹配里面的，比如前一个是一个加密的，放在请求头里，第二个 match 表示请求里的 ref 是个 master 分支，就可以区分分支进行不同操作，但是前面的加密配合 gogs 使用的时候有个问题(PS: webhook 的文档是真的烂)，gogs 设置 webhook 的加密是用的</p>
<blockquote>
<p>密钥文本将被用于计算推送内容的 SHA256 HMAC 哈希值，并设置为 <code>X-Gogs-Signature</code> 请求头的值。</p>
</blockquote>
<p>这种加密方式，所以 webhook 的这个示例的加密方式不行，但这货的文档里居然没有说明支持哪些加密，神TM，后来还是翻 <a href="https://github.com/adnanh/webhook/issues/289">issue</a> 翻到了, 需要使用这个<code>payload-hash-sha256</code></p>
<h2 id="执行脚本-redeploy-sh"><a href="#执行脚本-redeploy-sh" class="headerlink" title="执行脚本 redeploy.sh"></a>执行脚本 redeploy.sh</h2><p>脚本类似于这样</p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell">#!&#x2F;bin&#x2F;bash -e

function cleanup &#123;
      echo &quot;Error occoured&quot;
&#125;
trap cleanup ERR

commit_message&#x3D;$1 # head_commit.message
pusher_name&#x3D;$2 # pusher.name
commit_id&#x3D;$3 # head_commit.id


cd ~&#x2F;do-react-example-app&#x2F;
git pull origin master
yarn &amp;&amp; yarn build<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>就是简单的拉代码，然后构建下，真实使用时可能不是这样，因为页面会部署在 nginx 的作用目录，还需要 rsync 过去，这部分可能还涉及到两个问题第一个是使用 rsync 还是其他的 cp，不过这个无所谓；第二个是目录权限的问题，以我的系统ubuntu 为例，默认用户是 ubuntu，nginx 部署的目录是 www，所以需要切换用户等操作，一开始是想用在shell 文件中直接写了密码，但是不知道咋传，查了下是类似于这样 <code>echo &quot;passwd&quot; | sudo -S cmd</code>，通过管道命令往后传，然后就是这个<code>-S</code>, 参数的解释是<code>-S, --stdin                 read password from standard input</code>,但是这样么也不是太安全的赶脚，又看了下还有两种方法，</p>
<ul>
<li><p>就是给root 设置一个不需要密码的命令类似于这样，</p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell">myusername ALL &#x3D; (ALL) ALL
myusername ALL &#x3D; (root) NOPASSWD: &#x2F;path&#x2F;to&#x2F;my&#x2F;program<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre></li>
<li><p>另一种就是把默认用户跟 root 设置成同一个 group 的</p>
</li>
</ul>
<h2 id="使用"><a href="#使用" class="headerlink" title="使用"></a>使用</h2><p>真正实操的时候其实还有不少问题，首先运行 webhook 就碰到了我前面说的，使用 snap 运行的时候会找不到前面的 hooks.json配置文件，执行<code>snap run webhook -hooks /opt/hooks/hooks.json -verbose</code>就碰到下面的<code>couldn&#39;t load hooks from file! open /opt/hooks/hooks.json: no such file or directory</code>，后来直接下了个官方最新的 release，就直接执行 <code>webhook -hooks /opt/hooks/hooks.json -verbose</code> 就可以了，然后是前面的示例配置文件里的几个参数，比如<code>head_commit.message</code> 其实 gogs 推过来的根本没这玩意，而且都是数组，不知道咋取，烂文档，不过总比搭个 drone 好一点就忍了。补充一点就是在 debug 的时候需要看下问题出在哪，看看脚本有没有执行，所以需要在前面的 json 里加这个参数<code>&quot;include-command-output-in-response&quot;: true</code>, 就能输出来脚本执行结果</p>
]]></content>
      <categories>
        <category>持续集成</category>
      </categories>
      <tags>
        <tag>Gogs</tag>
        <tag>Webhook</tag>
      </tags>
  </entry>
  <entry>
    <title>invert-binary-tree</title>
    <url>/2015/06/22/invert-binary-tree/</url>
    <content><![CDATA[<p><strong>Invert a binary tree</strong></p>
<pre><code>     4
   /   \
  2     7
 / \   / \
1   3 6   9
</code></pre>
<p>to</p>
<pre><code>     4
   /   \
  7     2
 / \   / \
9   6 3   1
</code></pre>
<p><strong>Trivia:</strong><br>This problem was inspired by <a href="https://twitter.com/mxcl/status/608682016205344768">this original tweet</a> by <a href="https://twitter.com/mxcl">Max Howell</a>:</p>
<blockquote>
<p>Google: 90% of our engineers use the software you wrote (Homebrew),<br>but you can’t invert a binary tree on a whiteboard so fuck off.  </p>
</blockquote>
<pre class="line-numbers language-C++" data-language="C++"><code class="language-C++">&#x2F;**
 * Definition for a binary tree node.
 * struct TreeNode &#123;
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) &#123;&#125;
 * &#125;;
 *&#x2F;
class Solution &#123;
public:
    TreeNode* invertTree(TreeNode* root) &#123;
        if(root &#x3D;&#x3D; NULL) return root;
        TreeNode* temp;
        temp &#x3D; invertTree(root-&gt;left);
        root-&gt;left &#x3D; invertTree(root-&gt;right);
        root-&gt;right &#x3D; temp;
        return root;
    &#125;
&#125;;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>]]></content>
      <categories>
        <category>leetcode</category>
      </categories>
      <tags>
        <tag>leetcode</tag>
        <tag>c++</tag>
      </tags>
  </entry>
  <entry>
    <title>minimum-size-subarray-sum-209</title>
    <url>/2016/10/11/minimum-size-subarray-sum-209/</url>
    <content><![CDATA[<h3 id="problem"><a href="#problem" class="headerlink" title="problem"></a>problem</h3><p>Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the sum ≥ s. If there isn’t one, return 0 instead.  </p>
<p>For example, given the array <code>[2,3,1,2,4,3]</code> and <code>s = 7</code>,<br>the subarray <code>[4,3]</code> has the minimal length under the problem constraint.  </p>
<h4 id="题解"><a href="#题解" class="headerlink" title="题解"></a>题解</h4><p>参考，滑动窗口，跟之前Data Structure课上的online算法有点像，<a href="http://blog.csdn.net/lisonglisonglisong/article/details/45666975">链接</a>  </p>
<h4 id="Code"><a href="#Code" class="headerlink" title="Code"></a>Code</h4><pre class="line-numbers language-C++" data-language="C++"><code class="language-C++">class Solution &#123;
public:
    int minSubArrayLen(int s, vector&lt;int&gt;&amp; nums) &#123;
        int len &#x3D; nums.size();
        if(len &#x3D;&#x3D; 0) return 0;
        int minlen &#x3D; INT_MAX;
        int sum &#x3D; 0;
        
        int left &#x3D; 0;
        int right &#x3D; -1;
        while(right &lt; len)
        &#123;
            while(sum &lt; s &amp;&amp; right &lt; len)
                sum +&#x3D; nums[++right];
            if(sum &gt;&#x3D; s)
            &#123;
                minlen &#x3D; minlen &lt; right - left + 1 ? minlen : right - left + 1;
                sum -&#x3D; nums[left++];
            &#125;
        &#125;
        return minlen &gt; len ? 0 : minlen;
    &#125;
&#125;;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
]]></content>
      <categories>
        <category>leetcode</category>
      </categories>
      <tags>
        <tag>leetcode</tag>
        <tag>c++</tag>
      </tags>
  </entry>
  <entry>
    <title>C++ 指针使用中的一个小问题</title>
    <url>/2014/12/23/my-new-post/</url>
    <content><![CDATA[<h4 id="在工作中碰到的一点C-指针上的一点小问题"><a href="#在工作中碰到的一点C-指针上的一点小问题" class="headerlink" title="在工作中碰到的一点C++指针上的一点小问题"></a>在工作中碰到的一点C++指针上的一点小问题</h4><hr>
<p>在C++中，应该是从C语言就开始了，除了<a href="">void</a>型指针之外都是需要有分配对应的内存才可以使用，同时<a href="">malloc</a>与<a href="">free</a>成对使用，<a href="">new</a>与<a href="">delete</a>成对使用，否则造成内存泄漏。</p>
]]></content>
      <categories>
        <category>C++</category>
      </categories>
      <tags>
        <tag>博客，文章</tag>
      </tags>
  </entry>
  <entry>
    <title>mybatis 的 $ 和 # 是有啥区别</title>
    <url>/2020/09/06/mybatis-%E7%9A%84-%E5%92%8C-%E6%98%AF%E6%9C%89%E5%95%A5%E5%8C%BA%E5%88%AB/</url>
    <content><![CDATA[<p>这个问题也是面试中常被问到的，就抽空来了解下这个，跳过一大段前面初始化的逻辑，<br>对于一条<code>select * from t1 where id = #&#123;id&#125;</code>这样的 sql，在初始化扫描 mapper 的xml文件的时候会根据是否是 dynamic 来判断生成 DynamicSqlSource 还是 RawSqlSource，这里它是一条 RawSqlSource，<br>在这里做了替换，将<code>#&#123;&#125;</code>替换成了<code>?</code><br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/c84r0g.png"><br>前面说的是否 dynamic 就是在这里进行判断<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/E0ODcp.png"></p>
<pre class="line-numbers language-Java" data-language="Java"><code class="language-Java">&#x2F;&#x2F; org.apache.ibatis.scripting.xmltags.XMLScriptBuilder#parseScriptNode
public SqlSource parseScriptNode() &#123;
    MixedSqlNode rootSqlNode &#x3D; parseDynamicTags(context);
    SqlSource sqlSource;
    if (isDynamic) &#123;
      sqlSource &#x3D; new DynamicSqlSource(configuration, rootSqlNode);
    &#125; else &#123;
      sqlSource &#x3D; new RawSqlSource(configuration, rootSqlNode, parameterType);
    &#125;
    return sqlSource;
  &#125;
&#x2F;&#x2F; org.apache.ibatis.scripting.xmltags.XMLScriptBuilder#parseDynamicTags
protected MixedSqlNode parseDynamicTags(XNode node) &#123;
    List&lt;SqlNode&gt; contents &#x3D; new ArrayList&lt;&gt;();
    NodeList children &#x3D; node.getNode().getChildNodes();
    for (int i &#x3D; 0; i &lt; children.getLength(); i++) &#123;
      XNode child &#x3D; node.newXNode(children.item(i));
      if (child.getNode().getNodeType() &#x3D;&#x3D; Node.CDATA_SECTION_NODE || child.getNode().getNodeType() &#x3D;&#x3D; Node.TEXT_NODE) &#123;
        String data &#x3D; child.getStringBody(&quot;&quot;);
        TextSqlNode textSqlNode &#x3D; new TextSqlNode(data);
        if (textSqlNode.isDynamic()) &#123;
          contents.add(textSqlNode);
          isDynamic &#x3D; true;
        &#125; else &#123;
          contents.add(new StaticTextSqlNode(data));
        &#125;
      &#125; else if (child.getNode().getNodeType() &#x3D;&#x3D; Node.ELEMENT_NODE) &#123; &#x2F;&#x2F; issue #628
        String nodeName &#x3D; child.getNode().getNodeName();
        NodeHandler handler &#x3D; nodeHandlerMap.get(nodeName);
        if (handler &#x3D;&#x3D; null) &#123;
          throw new BuilderException(&quot;Unknown element &lt;&quot; + nodeName + &quot;&gt; in SQL statement.&quot;);
        &#125;
        handler.handleNode(child, contents);
        isDynamic &#x3D; true;
      &#125;
    &#125;
    return new MixedSqlNode(contents);
  &#125;
&#x2F;&#x2F; org.apache.ibatis.scripting.xmltags.TextSqlNode#isDynamic
  public boolean isDynamic() &#123;
    DynamicCheckerTokenParser checker &#x3D; new DynamicCheckerTokenParser();
    GenericTokenParser parser &#x3D; createParser(checker);
    parser.parse(text);
    return checker.isDynamic();
  &#125;
    private GenericTokenParser createParser(TokenHandler handler) &#123;
    return new GenericTokenParser(&quot;$&#123;&quot;, &quot;&#125;&quot;, handler);
  &#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>可以看到其中一个条件就是是否有<code>$&#123;&#125;</code>这种占位符，假如说上面的 sql 换成 <code>$&#123;&#125;</code>，那么可以看到它会在这里创建一个 dynamicSqlSource,</p>
<pre class="line-numbers language-Java" data-language="Java"><code class="language-Java">&#x2F;&#x2F; org.apache.ibatis.scripting.xmltags.DynamicSqlSource
public class DynamicSqlSource implements SqlSource &#123;

  private final Configuration configuration;
  private final SqlNode rootSqlNode;

  public DynamicSqlSource(Configuration configuration, SqlNode rootSqlNode) &#123;
    this.configuration &#x3D; configuration;
    this.rootSqlNode &#x3D; rootSqlNode;
  &#125;

  @Override
  public BoundSql getBoundSql(Object parameterObject) &#123;
    DynamicContext context &#x3D; new DynamicContext(configuration, parameterObject);
    rootSqlNode.apply(context);
    SqlSourceBuilder sqlSourceParser &#x3D; new SqlSourceBuilder(configuration);
    Class&lt;?&gt; parameterType &#x3D; parameterObject &#x3D;&#x3D; null ? Object.class : parameterObject.getClass();
    SqlSource sqlSource &#x3D; sqlSourceParser.parse(context.getSql(), parameterType, context.getBindings());
    BoundSql boundSql &#x3D; sqlSource.getBoundSql(parameterObject);
    context.getBindings().forEach(boundSql::setAdditionalParameter);
    return boundSql;
  &#125;

&#125;
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这里眼尖的同学可能就可以看出来了，RawSqlSource 在初始化的时候已经经过了 parse，把<code>#&#123;&#125;</code>替换成了<code>?</code>占位符，但是 DynamicSqlSource 并没有<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/dnZWP7.png">再看这个图，我们发现在这的时候还没有进行替换<br>然后往里跟<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/YGVD0P.png">好像是这里了<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/BWHuUO.png"><br>这里 rootSqlNode.apply 其实是一个对原来 sql 的解析结果的一个循环调用，不同类型的标签会构成不同的 node，像这里就是一个 textSqlNode<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/eTiQm6.png"><br>可以发现到这我们的 sql 已经被替换了，而且是直接作为 string 类型替换的，所以可以明白了这个问题所在，就是注入，不过细心的同学发现其实这里是有个<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/Cc4JPw.png"><br>理论上还是可以做过滤的，不过好像现在没用起来。<br>我们前面可以发现对于<code>#&#123;&#125;</code>是在启动扫描 mapper的 xml 文件就替换成了 <code>?</code>,然后是在什么时候变成实际的值的呢<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/fRHpNO.png"><br>发现到这的时候还是没有替换，其实说白了也就是 prepareStatement 那一套，<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/4tNU7f.png"><br>在这里进行替换，会拿到 org.apache.ibatis.mapping.ParameterMapping，然后进行替换，因为会带着类型信息，所以不用担心注入咯</p>
]]></content>
      <categories>
        <category>Java</category>
        <category>Mybatis</category>
        <category>Mysql</category>
        <category>Sql注入</category>
        <category>Spring</category>
        <category>Mybatis</category>
      </categories>
      <tags>
        <tag>Java</tag>
        <tag>Mysql</tag>
        <tag>Mybatis</tag>
        <tag>Sql注入</tag>
      </tags>
  </entry>
  <entry>
    <title>mybatis 的缓存是怎么回事</title>
    <url>/2020/10/03/mybatis-%E7%9A%84%E7%BC%93%E5%AD%98%E6%98%AF%E6%80%8E%E4%B9%88%E5%9B%9E%E4%BA%8B/</url>
    <content><![CDATA[<p>Java 真的是任何一个中间件，比较常用的那种，都有很多内容值得深挖，比如这个缓存，慢慢有过一些感悟，比如如何提升性能，缓存无疑是一大重要手段，最底层开始 CPU 就有缓存，而且又小又贵，再往上一点内存一般作为硬盘存储在运行时的存储，一般在代码里也会用内存作为一些本地缓存，譬如数据库，像 mysql 这种也是有innodb_buffer_pool来提升查询效率，本质上理解就是用更快的存储作为相对慢存储的缓存，减少查询直接访问较慢的存储，并且这个都是相对的，比起 cpu 的缓存，那内存也是渣，但是与普通机械硬盘相比，那也是两个次元的水平。</p>
<p>闲扯这么多来说说 mybatis 的缓存，mybatis 一般作为一个轻量级的 orm 使用，相对应的就是比较重量级的 hibernate，不过不在这次讨论范围，上一次是主要讲了 mybatis 在解析 sql 过程中，对于两种占位符的不同替换实现策略，这次主要聊下 mybatis 的缓存，前面其实得了解下前置的东西，比如 sqlsession，先当做我们知道 sqlsession 是个什么玩意，可能或多或少的知道 mybatis 是有两级缓存，</p>
<h3 id="一级缓存"><a href="#一级缓存" class="headerlink" title="一级缓存"></a>一级缓存</h3><p>第一级的缓存是在 <a href="https://github.com/mybatis/mybatis-3/blob/master/src/main/java/org/apache/ibatis/executor/BaseExecutor.java#L65">BaseExecutor</a> 中的 <a href="https://github.com/mybatis/mybatis-3/blob/master/src/main/java/org/apache/ibatis/cache/impl/PerpetualCache.java#L27">PerpetualCache</a>，它是个最基本的缓存实现类，使用了 HashMap 实现缓存功能，代码其实没几十行</p>
<pre class="line-numbers language-Java" data-language="Java"><code class="language-Java">public class PerpetualCache implements Cache &#123;

  private final String id;

  private final Map&lt;Object, Object&gt; cache &#x3D; new HashMap&lt;&gt;();

  public PerpetualCache(String id) &#123;
    this.id &#x3D; id;
  &#125;

  @Override
  public String getId() &#123;
    return id;
  &#125;

  @Override
  public int getSize() &#123;
    return cache.size();
  &#125;

  @Override
  public void putObject(Object key, Object value) &#123;
    cache.put(key, value);
  &#125;

  @Override
  public Object getObject(Object key) &#123;
    return cache.get(key);
  &#125;

  @Override
  public Object removeObject(Object key) &#123;
    return cache.remove(key);
  &#125;

  @Override
  public void clear() &#123;
    cache.clear();
  &#125;

  @Override
  public boolean equals(Object o) &#123;
    if (getId() &#x3D;&#x3D; null) &#123;
      throw new CacheException(&quot;Cache instances require an ID.&quot;);
    &#125;
    if (this &#x3D;&#x3D; o) &#123;
      return true;
    &#125;
    if (!(o instanceof Cache)) &#123;
      return false;
    &#125;

    Cache otherCache &#x3D; (Cache) o;
    return getId().equals(otherCache.getId());
  &#125;

  @Override
  public int hashCode() &#123;
    if (getId() &#x3D;&#x3D; null) &#123;
      throw new CacheException(&quot;Cache instances require an ID.&quot;);
    &#125;
    return getId().hashCode();
  &#125;

&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>可以看一下BaseExecutor 的构造函数</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">protected</span> <span class="token class-name">BaseExecutor</span><span class="token punctuation">(</span><span class="token class-name">Configuration</span> configuration<span class="token punctuation">,</span> <span class="token class-name">Transaction</span> transaction<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>transaction <span class="token operator">=</span> transaction<span class="token punctuation">;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>deferredLoads <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ConcurrentLinkedQueue</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>localCache <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">PerpetualCache</span><span class="token punctuation">(</span><span class="token string">"LocalCache"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>localOutputParameterCache <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">PerpetualCache</span><span class="token punctuation">(</span><span class="token string">"LocalOutputParameterCache"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>closed <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>configuration <span class="token operator">=</span> configuration<span class="token punctuation">;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>wrapper <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>就是把 PerpetualCache 作为 localCache，然后怎么使用我看简单看一下，BaseExecutor 的查询首先是调用这个函数</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Override</span>
  <span class="token keyword">public</span> <span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">E</span><span class="token punctuation">></span></span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">E</span><span class="token punctuation">></span></span> <span class="token function">query</span><span class="token punctuation">(</span><span class="token class-name">MappedStatement</span> ms<span class="token punctuation">,</span> <span class="token class-name">Object</span> parameter<span class="token punctuation">,</span> <span class="token class-name">RowBounds</span> rowBounds<span class="token punctuation">,</span> <span class="token class-name">ResultHandler</span> resultHandler<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">SQLException</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">BoundSql</span> boundSql <span class="token operator">=</span> ms<span class="token punctuation">.</span><span class="token function">getBoundSql</span><span class="token punctuation">(</span>parameter<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">CacheKey</span> key <span class="token operator">=</span> <span class="token function">createCacheKey</span><span class="token punctuation">(</span>ms<span class="token punctuation">,</span> parameter<span class="token punctuation">,</span> rowBounds<span class="token punctuation">,</span> boundSql<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token function">query</span><span class="token punctuation">(</span>ms<span class="token punctuation">,</span> parameter<span class="token punctuation">,</span> rowBounds<span class="token punctuation">,</span> resultHandler<span class="token punctuation">,</span> key<span class="token punctuation">,</span> boundSql<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>可以看到首先是调用了 <a href="https://github.com/mybatis/mybatis-3/blob/master/src/main/java/org/apache/ibatis/executor/BaseExecutor.java#L195">createCacheKey</a> 方法，这个方法呢，先不看怎么写的，如果我们自己要实现这么个缓存，首先这个缓存 key 的设计也是个问题，如果是以表名加主键作为 key，那么分页查询，或者没有主键的时候就不行，来看看 mybatis 是怎么设计的</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Override</span>
  <span class="token keyword">public</span> <span class="token class-name">CacheKey</span> <span class="token function">createCacheKey</span><span class="token punctuation">(</span><span class="token class-name">MappedStatement</span> ms<span class="token punctuation">,</span> <span class="token class-name">Object</span> parameterObject<span class="token punctuation">,</span> <span class="token class-name">RowBounds</span> rowBounds<span class="token punctuation">,</span> <span class="token class-name">BoundSql</span> boundSql<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>closed<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
      <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">ExecutorException</span><span class="token punctuation">(</span><span class="token string">"Executor was closed."</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token class-name">CacheKey</span> cacheKey <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">CacheKey</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    cacheKey<span class="token punctuation">.</span><span class="token function">update</span><span class="token punctuation">(</span>ms<span class="token punctuation">.</span><span class="token function">getId</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    cacheKey<span class="token punctuation">.</span><span class="token function">update</span><span class="token punctuation">(</span>rowBounds<span class="token punctuation">.</span><span class="token function">getOffset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    cacheKey<span class="token punctuation">.</span><span class="token function">update</span><span class="token punctuation">(</span>rowBounds<span class="token punctuation">.</span><span class="token function">getLimit</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    cacheKey<span class="token punctuation">.</span><span class="token function">update</span><span class="token punctuation">(</span>boundSql<span class="token punctuation">.</span><span class="token function">getSql</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">ParameterMapping</span><span class="token punctuation">></span></span> parameterMappings <span class="token operator">=</span> boundSql<span class="token punctuation">.</span><span class="token function">getParameterMappings</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">TypeHandlerRegistry</span> typeHandlerRegistry <span class="token operator">=</span> ms<span class="token punctuation">.</span><span class="token function">getConfiguration</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getTypeHandlerRegistry</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">// mimic DefaultParameterHandler logic</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">ParameterMapping</span> parameterMapping <span class="token operator">:</span> parameterMappings<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
      <span class="token keyword">if</span> <span class="token punctuation">(</span>parameterMapping<span class="token punctuation">.</span><span class="token function">getMode</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">!=</span> <span class="token class-name">ParameterMode</span><span class="token punctuation">.</span>OUT<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">Object</span> value<span class="token punctuation">;</span>
        <span class="token class-name">String</span> propertyName <span class="token operator">=</span> parameterMapping<span class="token punctuation">.</span><span class="token function">getProperty</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>boundSql<span class="token punctuation">.</span><span class="token function">hasAdditionalParameter</span><span class="token punctuation">(</span>propertyName<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
          value <span class="token operator">=</span> boundSql<span class="token punctuation">.</span><span class="token function">getAdditionalParameter</span><span class="token punctuation">(</span>propertyName<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>parameterObject <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
          value <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>typeHandlerRegistry<span class="token punctuation">.</span><span class="token function">hasTypeHandler</span><span class="token punctuation">(</span>parameterObject<span class="token punctuation">.</span><span class="token function">getClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
          value <span class="token operator">=</span> parameterObject<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
          <span class="token class-name">MetaObject</span> metaObject <span class="token operator">=</span> configuration<span class="token punctuation">.</span><span class="token function">newMetaObject</span><span class="token punctuation">(</span>parameterObject<span class="token punctuation">)</span><span class="token punctuation">;</span>
          value <span class="token operator">=</span> metaObject<span class="token punctuation">.</span><span class="token function">getValue</span><span class="token punctuation">(</span>propertyName<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        cacheKey<span class="token punctuation">.</span><span class="token function">update</span><span class="token punctuation">(</span>value<span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>configuration<span class="token punctuation">.</span><span class="token function">getEnvironment</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
      <span class="token comment">// issue #176</span>
      cacheKey<span class="token punctuation">.</span><span class="token function">update</span><span class="token punctuation">(</span>configuration<span class="token punctuation">.</span><span class="token function">getEnvironment</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getId</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">return</span> cacheKey<span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>首先需要 id，这个 id 是 mapper 里方法的 id， 然后是偏移量跟返回行数，再就是 sql，然后是参数，基本上是会有影响的都加进去了，在这个 update 里面</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">update</span><span class="token punctuation">(</span><span class="token class-name">Object</span> object<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">int</span> baseHashCode <span class="token operator">=</span> object <span class="token operator">==</span> <span class="token keyword">null</span> <span class="token operator">?</span> <span class="token number">1</span> <span class="token operator">:</span> <span class="token class-name">ArrayUtil</span><span class="token punctuation">.</span><span class="token function">hashCode</span><span class="token punctuation">(</span>object<span class="token punctuation">)</span><span class="token punctuation">;</span>

    count<span class="token operator">++</span><span class="token punctuation">;</span>
    checksum <span class="token operator">+=</span> baseHashCode<span class="token punctuation">;</span>
    baseHashCode <span class="token operator">*=</span> count<span class="token punctuation">;</span>

    hashcode <span class="token operator">=</span> multiplier <span class="token operator">*</span> hashcode <span class="token operator">+</span> baseHashCode<span class="token punctuation">;</span>

    updateList<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>object<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>其实是一个 hash 转换，具体不纠结，就是提高特异性，然后回来就是继续调用 query</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Override</span>
  <span class="token keyword">public</span> <span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">E</span><span class="token punctuation">></span></span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">E</span><span class="token punctuation">></span></span> <span class="token function">query</span><span class="token punctuation">(</span><span class="token class-name">MappedStatement</span> ms<span class="token punctuation">,</span> <span class="token class-name">Object</span> parameter<span class="token punctuation">,</span> <span class="token class-name">RowBounds</span> rowBounds<span class="token punctuation">,</span> <span class="token class-name">ResultHandler</span> resultHandler<span class="token punctuation">,</span> <span class="token class-name">CacheKey</span> key<span class="token punctuation">,</span> <span class="token class-name">BoundSql</span> boundSql<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">SQLException</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">ErrorContext</span><span class="token punctuation">.</span><span class="token function">instance</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">resource</span><span class="token punctuation">(</span>ms<span class="token punctuation">.</span><span class="token function">getResource</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">activity</span><span class="token punctuation">(</span><span class="token string">"executing a query"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">object</span><span class="token punctuation">(</span>ms<span class="token punctuation">.</span><span class="token function">getId</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>closed<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
      <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">ExecutorException</span><span class="token punctuation">(</span><span class="token string">"Executor was closed."</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>queryStack <span class="token operator">==</span> <span class="token number">0</span> <span class="token operator">&amp;&amp;</span> ms<span class="token punctuation">.</span><span class="token function">isFlushCacheRequired</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
      <span class="token function">clearLocalCache</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">E</span><span class="token punctuation">></span></span> list<span class="token punctuation">;</span>
    <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
      queryStack<span class="token operator">++</span><span class="token punctuation">;</span>
      list <span class="token operator">=</span> resultHandler <span class="token operator">==</span> <span class="token keyword">null</span> <span class="token operator">?</span> <span class="token punctuation">(</span><span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">E</span><span class="token punctuation">></span></span><span class="token punctuation">)</span> localCache<span class="token punctuation">.</span><span class="token function">getObject</span><span class="token punctuation">(</span>key<span class="token punctuation">)</span> <span class="token operator">:</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
      <span class="token keyword">if</span> <span class="token punctuation">(</span>list <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token function">handleLocallyCachedOutputParameters</span><span class="token punctuation">(</span>ms<span class="token punctuation">,</span> key<span class="token punctuation">,</span> parameter<span class="token punctuation">,</span> boundSql<span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
        list <span class="token operator">=</span> <span class="token function">queryFromDatabase</span><span class="token punctuation">(</span>ms<span class="token punctuation">,</span> parameter<span class="token punctuation">,</span> rowBounds<span class="token punctuation">,</span> resultHandler<span class="token punctuation">,</span> key<span class="token punctuation">,</span> boundSql<span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span> <span class="token keyword">finally</span> <span class="token punctuation">&#123;</span>
      queryStack<span class="token operator">--</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>queryStack <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
      <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">DeferredLoad</span> deferredLoad <span class="token operator">:</span> deferredLoads<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        deferredLoad<span class="token punctuation">.</span><span class="token function">load</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">&#125;</span>
      <span class="token comment">// issue #601</span>
      deferredLoads<span class="token punctuation">.</span><span class="token function">clear</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token keyword">if</span> <span class="token punctuation">(</span>configuration<span class="token punctuation">.</span><span class="token function">getLocalCacheScope</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token class-name">LocalCacheScope</span><span class="token punctuation">.</span>STATEMENT<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">// issue #482</span>
        <span class="token function">clearLocalCache</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">return</span> list<span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>可以看到是先从 localCache 里取，取不到再 queryFromDatabase，其实比较简单，这是一级缓存，考虑到 sqlsession 跟 BaseExecutor 的关系，其实是随着 sqlsession 来保证这个缓存不会出现脏数据幻读的情况，当然事务相关的后面可能再单独聊。</p>
<h3 id="二级缓存"><a href="#二级缓存" class="headerlink" title="二级缓存"></a>二级缓存</h3><p>其实这个一级二级顺序有点反过来，其实查询的是先走的二级缓存，当然二级的需要配置开启，默认不开，<br>需要通过</p>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>setting</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>cacheEnabled<span class="token punctuation">"</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>true<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>来开启，然后我们的查询就会走到</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">CachingExecutor</span> <span class="token keyword">implements</span> <span class="token class-name">Executor</span> <span class="token punctuation">&#123;</span>

  <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token class-name">Executor</span> delegate<span class="token punctuation">;</span>
  <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token class-name">TransactionalCacheManager</span> tcm <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">TransactionalCacheManager</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>这个 Executor 中，这里我放了类里面的元素，发现没有一个 Cache 类，这就是一个特点了，往下看查询过程</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Override</span>
  <span class="token keyword">public</span> <span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">E</span><span class="token punctuation">></span></span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">E</span><span class="token punctuation">></span></span> <span class="token function">query</span><span class="token punctuation">(</span><span class="token class-name">MappedStatement</span> ms<span class="token punctuation">,</span> <span class="token class-name">Object</span> parameterObject<span class="token punctuation">,</span> <span class="token class-name">RowBounds</span> rowBounds<span class="token punctuation">,</span> <span class="token class-name">ResultHandler</span> resultHandler<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">SQLException</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">BoundSql</span> boundSql <span class="token operator">=</span> ms<span class="token punctuation">.</span><span class="token function">getBoundSql</span><span class="token punctuation">(</span>parameterObject<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">CacheKey</span> key <span class="token operator">=</span> <span class="token function">createCacheKey</span><span class="token punctuation">(</span>ms<span class="token punctuation">,</span> parameterObject<span class="token punctuation">,</span> rowBounds<span class="token punctuation">,</span> boundSql<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token function">query</span><span class="token punctuation">(</span>ms<span class="token punctuation">,</span> parameterObject<span class="token punctuation">,</span> rowBounds<span class="token punctuation">,</span> resultHandler<span class="token punctuation">,</span> key<span class="token punctuation">,</span> boundSql<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span>

  <span class="token annotation punctuation">@Override</span>
  <span class="token keyword">public</span> <span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">E</span><span class="token punctuation">></span></span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">E</span><span class="token punctuation">></span></span> <span class="token function">query</span><span class="token punctuation">(</span><span class="token class-name">MappedStatement</span> ms<span class="token punctuation">,</span> <span class="token class-name">Object</span> parameterObject<span class="token punctuation">,</span> <span class="token class-name">RowBounds</span> rowBounds<span class="token punctuation">,</span> <span class="token class-name">ResultHandler</span> resultHandler<span class="token punctuation">,</span> <span class="token class-name">CacheKey</span> key<span class="token punctuation">,</span> <span class="token class-name">BoundSql</span> boundSql<span class="token punctuation">)</span>
      <span class="token keyword">throws</span> <span class="token class-name">SQLException</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">Cache</span> cache <span class="token operator">=</span> ms<span class="token punctuation">.</span><span class="token function">getCache</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>cache <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
      <span class="token function">flushCacheIfRequired</span><span class="token punctuation">(</span>ms<span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token keyword">if</span> <span class="token punctuation">(</span>ms<span class="token punctuation">.</span><span class="token function">isUseCache</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> resultHandler <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token function">ensureNoOutParams</span><span class="token punctuation">(</span>ms<span class="token punctuation">,</span> boundSql<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token annotation punctuation">@SuppressWarnings</span><span class="token punctuation">(</span><span class="token string">"unchecked"</span><span class="token punctuation">)</span>
        <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">E</span><span class="token punctuation">></span></span> list <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">E</span><span class="token punctuation">></span></span><span class="token punctuation">)</span> tcm<span class="token punctuation">.</span><span class="token function">getObject</span><span class="token punctuation">(</span>cache<span class="token punctuation">,</span> key<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>list <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
          list <span class="token operator">=</span> delegate<span class="token punctuation">.</span><span class="token function">query</span><span class="token punctuation">(</span>ms<span class="token punctuation">,</span> parameterObject<span class="token punctuation">,</span> rowBounds<span class="token punctuation">,</span> resultHandler<span class="token punctuation">,</span> key<span class="token punctuation">,</span> boundSql<span class="token punctuation">)</span><span class="token punctuation">;</span>
          tcm<span class="token punctuation">.</span><span class="token function">putObject</span><span class="token punctuation">(</span>cache<span class="token punctuation">,</span> key<span class="token punctuation">,</span> list<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// issue #578 and #116</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">return</span> list<span class="token punctuation">;</span>
      <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">return</span> delegate<span class="token punctuation">.</span><span class="token function">query</span><span class="token punctuation">(</span>ms<span class="token punctuation">,</span> parameterObject<span class="token punctuation">,</span> rowBounds<span class="token punctuation">,</span> resultHandler<span class="token punctuation">,</span> key<span class="token punctuation">,</span> boundSql<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>看到没，其实缓存是从 tcm 这个成员变量里取，而这个是什么呢，事务性缓存(直译下)，因为这个其实是用 MappedStatement 里的 Cache 作为key 从 tcm 的 map 取出来的</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">TransactionalCacheManager</span> <span class="token punctuation">&#123;</span>

  <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token class-name">Map</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Cache</span><span class="token punctuation">,</span> <span class="token class-name">TransactionalCache</span><span class="token punctuation">></span></span> transactionalCaches <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">HashMap</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>MappedStatement是被全局使用的，所以其实二级缓存是跟着 mapper 的 namespace 走的，可以被多个 CachingExecutor 获取到，就会出现线程安全问题，线程安全问题可以用SynchronizedCache来解决，就是加锁，但是对于事务中的脏读，使用了TransactionalCache来解决这个问题，</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">TransactionalCache</span> <span class="token keyword">implements</span> <span class="token class-name">Cache</span> <span class="token punctuation">&#123;</span>

  <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">final</span> <span class="token class-name">Log</span> log <span class="token operator">=</span> <span class="token class-name">LogFactory</span><span class="token punctuation">.</span><span class="token function">getLog</span><span class="token punctuation">(</span><span class="token class-name">TransactionalCache</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token class-name">Cache</span> delegate<span class="token punctuation">;</span>
  <span class="token keyword">private</span> <span class="token keyword">boolean</span> clearOnCommit<span class="token punctuation">;</span>
  <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token class-name">Map</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Object</span><span class="token punctuation">,</span> <span class="token class-name">Object</span><span class="token punctuation">></span></span> entriesToAddOnCommit<span class="token punctuation">;</span>
  <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token class-name">Set</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Object</span><span class="token punctuation">></span></span> entriesMissedInCache<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>在事务还没提交的时候，会把中间状态的数据放在 entriesToAddOnCommit 中，只有在提交后会放进共享缓存中，</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">commit</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>clearOnCommit<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
      delegate<span class="token punctuation">.</span><span class="token function">clear</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token function">flushPendingEntries</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">reset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>]]></content>
      <categories>
        <category>Java</category>
        <category>Mybatis</category>
        <category>Mybatis</category>
        <category>缓存</category>
        <category>Spring</category>
        <category>Mybatis</category>
      </categories>
      <tags>
        <tag>Java</tag>
        <tag>Mysql</tag>
        <tag>Mybatis</tag>
        <tag>缓存</tag>
      </tags>
  </entry>
  <entry>
    <title>openresty</title>
    <url>/2019/06/18/openresty/</url>
    <content><![CDATA[<p>目前公司要对一些新的产品功能做灰度测试，因为在后端业务代码层面添加判断比较麻烦，所以想在nginx上做点手脚，就想到了openresty<br>前后也踩了不少坑，这边先写一点</p>
<p>首先是日志<br><code>error_log logs/error.log debug;</code><br>需要nginx开启日志的debug才能看到日志</p>
<p>使用 <code>lua_code_cache off</code>即可, 另外注意只有使用 <code>content_by_lua_file</code> 才会生效</p>
<pre class="line-numbers language-lua" data-language="lua"><code class="language-lua"><span class="token function">http</span> <span class="token punctuation">&#123;</span>
  lua_code_cache off<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>

location <span class="token operator">~</span><span class="token operator">*</span> <span class="token operator">/</span><span class="token punctuation">(</span>\d<span class="token operator">+</span><span class="token operator">-</span><span class="token punctuation">.</span><span class="token operator">*</span><span class="token punctuation">)</span><span class="token operator">/</span>api<span class="token operator">/</span>orgunits<span class="token operator">/</span><span class="token function">load_all</span><span class="token punctuation">(</span><span class="token punctuation">.</span><span class="token operator">*</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
   default_type <span class="token string">'application/json;charset=utf-8'</span><span class="token punctuation">;</span>
   content_by_lua_file <span class="token operator">/</span>data<span class="token operator">/</span>projects<span class="token operator">/</span>xxx<span class="token operator">/</span>current<span class="token operator">/</span>lua<span class="token operator">/</span>controller<span class="token operator">/</span>load_data<span class="token punctuation">.</span>lua<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>使用lua给nginx请求response头添加内容可以用这个</p>
<pre class="line-numbers language-lua" data-language="lua"><code class="language-lua">ngx<span class="token punctuation">.</span>header<span class="token punctuation">[</span><span class="token string">'response'</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token string">'header'</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>


<p><a href="http://cyukang.com/2017/05/22/try-on-openresty.html">使用总结</a></p>
<p>后续：</p>
<ol>
<li>一开始在本地环境的时候使用content_by_lua_file只关注了头，后来发到测试环境发现请求内容都没代理转发到后端服务上<br>网上查了下发现content_by_lua_file是将请求的所有内容包括response都用这里面的lua脚本生成了，content这个词就表示是请求内容<br>后来改成了access_by_lua_file就正常了，只是要去获取请求内容和修改响应头，并不是要完整的接管请求</li>
</ol>
<ol start="2">
<li><p>后来又碰到了一个坑是nginx有个client_body_buffer_size的配置参数，nginx在32位和64位系统里有8K和16K两个默认值，当请求内容大于这两个值的时候，会把请求内容放到临时文件里，这个时候openresty里的ngx.req.get_post_args()就会报“failed to get post args: requesty body in temp file not supported”这个错误，将client_body_buffer_size这个参数配置调大一点就好了</p>
</li>
<li><p>还有就是lua的异常捕获，网上看一般是用pcall和xpcall来进行保护调用，因为问题主要出在cjson的decode，这里有两个解决方案，一个就是将cjson.decode使用pcall封装，</p>
 <pre class="line-numbers language-lua" data-language="lua"><code class="language-lua"><span class="token keyword">local</span> decode <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">"cjson"</span><span class="token punctuation">)</span><span class="token punctuation">.</span>decode

<span class="token keyword">function</span> <span class="token function">json_decode</span><span class="token punctuation">(</span> str <span class="token punctuation">)</span>
    <span class="token keyword">local</span> ok<span class="token punctuation">,</span> t <span class="token operator">=</span> <span class="token function">pcall</span><span class="token punctuation">(</span>decode<span class="token punctuation">,</span> str<span class="token punctuation">)</span>
    <span class="token keyword">if</span> <span class="token keyword">not</span> ok <span class="token keyword">then</span>
      <span class="token keyword">return</span> <span class="token keyword">nil</span>
    <span class="token keyword">end</span>

    <span class="token keyword">return</span> t
<span class="token keyword">end</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p> 这个是使用了pcall，称为保护调用，会在内部错误后返回两个参数，第一个是false，第二个是错误信息<br> 还有一种是使用cjson.safe包</p>
 <pre class="line-numbers language-lua" data-language="lua"><code class="language-lua"><span class="token keyword">local</span> json <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">"cjson.safe"</span><span class="token punctuation">)</span>
<span class="token keyword">local</span> str <span class="token operator">=</span> <span class="token string">[[ &#123;"key:"value"&#125; ]]</span>

<span class="token keyword">local</span> t <span class="token operator">=</span> json<span class="token punctuation">.</span><span class="token function">decode</span><span class="token punctuation">(</span>str<span class="token punctuation">)</span>
<span class="token keyword">if</span> t <span class="token keyword">then</span>
    ngx<span class="token punctuation">.</span><span class="token function">say</span><span class="token punctuation">(</span><span class="token string">" --> "</span><span class="token punctuation">,</span> <span class="token function">type</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token keyword">end</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p> cjson.safe包会在解析失败的时候返回nil</p>
</li>
<li><p>还有一个是redis链接时如果host使用的是域名的话会提示“failed to connect: no resolver defined to resolve “redis.xxxxxx.com””，这里需要使用nginx的resolver指令，<br><code>resolver 8.8.8.8 valid=3600s;</code></p>
</li>
<li><p>还有一点补充下<br>就是业务在使用redis的时候使用了db的特性，所以在lua访问redis的时候也需要执行db，这里lua的redis库也支持了这个特性，可以使用instance:select(config:get(‘db’))来切换db</p>
</li>
<li><p>性能优化tips<br><a href="https://juejin.im/entry/5b0e8fcef265da09210072a3#openresty">建议是尽量少使用阶段钩子，例如content_by_lua_file，*_by_lua</a></p>
</li>
<li><p>发现一个不错的openresty站点<br><a href="http://orhub.org/">地址</a></p>
</li>
</ol>
]]></content>
      <categories>
        <category>nginx</category>
      </categories>
      <tags>
        <tag>openresty</tag>
        <tag>nginx</tag>
      </tags>
  </entry>
  <entry>
    <title>pcre-intro-and-a-simple-package</title>
    <url>/2015/01/16/pcre-intro-and-a-simple-package/</url>
    <content><![CDATA[<h3 id="Pcre"><a href="#Pcre" class="headerlink" title="Pcre"></a><a href="http://www.pcre.org/">Pcre</a></h3><blockquote>
<p>Perl Compatible Regular Expressions (PCRE) is a regular<br> expression C library inspired by the regular expression<br> capabilities in the Perl programming language, written<br> by Philip Hazel, starting in summer 1997.</p>
</blockquote>
<p>因为最近工作内容的一部分需要做字符串的识别处理，所以就顺便用上了之前在PHP中用过的正则，在C/C++中本身不包含正则库，这里使用的pcre，对MFC开发，在<a href="http://www.psyon.org/projects/pcre-win32/index.php">这里</a>提供了静态链接库，在引入lib跟.h文件后即可使用。</p>
<span id="more"></span>

<h3 id="Regular-Expression-Syntax"><a href="#Regular-Expression-Syntax" class="headerlink" title="Regular Expression Syntax"></a>Regular Expression Syntax</h3><p>然后是一些<a href="http://www.pcre.org/original/doc/html/pcresyntax.html">正则语法</a>，官方的语法文档比较科学严谨，特别是对类似于贪婪匹配等细节的说明，当然一般的使用可以在网上找到很多匹配语法，例如<a href="http://www.regextester.com/pregsyntax.html">这个</a>。</p>
<h3 id="PCRE函数介绍"><a href="#PCRE函数介绍" class="headerlink" title="PCRE函数介绍"></a>PCRE函数介绍</h3><blockquote>
<p>pcre_compile<br>原型：</p>
</blockquote>
<pre class="line-numbers language-C++" data-language="C++"><code class="language-C++">#include &lt;pcre.h&gt;
pcre *pcre_compile(const char *pattern, int options, const char **errptr, int *erroffset, const unsigned char *tableptr);<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>功能：将一个正则表达式编译成一个内部表示，在匹配多个字符串时，可以加速匹配。其同pcre_compile2功能一样只是缺少一个参数errorcodeptr。<br>参数：<br><code>pattern</code>   正则表达式<br><code>options</code>     为0，或者其他参数选项<br><code>errptr</code>       出错消息<br><code>erroffset</code>  出错位置<br><code>tableptr</code>   指向一个字符数组的指针，可以设置为空NULL</p>
<blockquote>
<p>pcre_exec<br>原型：</p>
</blockquote>
<pre class="line-numbers language-C++" data-language="C++"><code class="language-C++">#include &lt;pcre.h&gt;
int pcre_exec(const pcre *code, const pcre_extra *extra, const char *subject, int length, int startoffset, int options, int *ovector, int ovecsize)<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>功能：使用编译好的模式进行匹配，采用与Perl相似的算法，返回匹配串的偏移位置。<br>参数：<br><code>code</code>         编译好的模式<br><code>extra</code>        指向一个pcre_extra结构体，可以为NULL<br><code>subject</code>      需要匹配的字符串<br><code>length</code>       匹配的字符串长度（Byte）<br><code>startoffset</code>  匹配的开始位置<br><code>options</code>      选项位<br><code>ovector</code>      指向一个结果的整型数组<br><code>ovecsize</code>     数组大小。</p>
<p>这里是两个最常用的函数的简单说明，pcre的静态库提供了一系列的函数以供使用，可以参考这个<a href="http://blog.csdn.net/sulliy/article/details/6247155">博客</a>说明，另外对于以上函数的具体参数详细说明可以参考官网<a href="http://www.pcre.org/original/doc/html/">此处</a></p>
<h3 id="一个丑陋的封装"><a href="#一个丑陋的封装" class="headerlink" title="一个丑陋的封装"></a>一个丑陋的封装</h3><pre class="line-numbers language-C++" data-language="C++"><code class="language-C++">void COcxDemoDlg::pcre_exec_all(const pcre * re, PCRE_SPTR src, vector&lt;pair&lt;int, int&gt;&gt; &amp;vc)
&#123;
	int rc;
	int ovector[30];
	int i &#x3D; 0;
	pair&lt;int, int&gt; pr;
	rc &#x3D; pcre_exec(re, NULL, src, strlen(src), i, 0, ovector, 30);
	for (; rc &gt; 0;)
	&#123;
		i &#x3D; ovector[1];
		pr.first &#x3D; ovector[2];
		pr.second &#x3D; ovector[3];
		vc.push_back(pr);
		rc &#x3D; pcre_exec(re, NULL, src, strlen(src), i, 0, ovector, 30);
	&#125;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>vector中是全文匹配后的索引对，只是简单地用下。</p>
]]></content>
      <categories>
        <category>C++</category>
      </categories>
      <tags>
        <tag>c++</tag>
        <tag>mfc</tag>
      </tags>
  </entry>
  <entry>
    <title>php-abstract-class-and-interface</title>
    <url>/2016/11/10/php-abstract-class-and-interface/</url>
    <content><![CDATA[<h2 id="PHP抽象类和接口"><a href="#PHP抽象类和接口" class="headerlink" title="PHP抽象类和接口"></a>PHP抽象类和接口</h2><ul>
<li>抽象类与接口</li>
<li>抽象类内可以包含非抽象函数，即可实现函数</li>
<li>抽象类内必须包含至少一个抽象方法，抽象类和接口均不能实例化</li>
<li>抽象类可以设置访问级别，接口默认都是public</li>
<li>类可以实现多个接口但不能继承多个抽象类</li>
<li>类必须实现抽象类和接口里的抽象方法，不一定要实现抽象类的非抽象方法</li>
<li>接口内不能定义变量，但是可以定义常量</li>
</ul>
<h2 id="示例代码"><a href="#示例代码" class="headerlink" title="示例代码"></a>示例代码</h2><pre class="line-numbers language-none"><code class="language-none">&lt;?php
interface int1&#123;
    const INTER1 &#x3D; 111;
    function inter1();
&#125;
interface int2&#123;
    const INTER1 &#x3D; 222;
    function inter2();
&#125;
abstract class abst1&#123;
    public function abstr1()&#123;
        echo 1111;
    &#125;
    abstract function abstra1()&#123;
        echo &#39;ahahahha&#39;;
    &#125;
&#125;
abstract class abst2&#123;
    public function abstr2()&#123;
        echo 1111;
    &#125;
    abstract function abstra2();
&#125;
class normal1 extends abst1&#123;
    protected function abstr2()&#123;
        echo 222;
    &#125;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="result"><a href="#result" class="headerlink" title="result"></a>result</h2><pre class="line-numbers language-none"><code class="language-none">PHP Fatal error:  Abstract function abst1::abstra1() cannot contain body in new.php on line 17

Fatal error: Abstract function abst1::abstra1() cannot contain body in php on line 17<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
]]></content>
      <categories>
        <category>php</category>
      </categories>
      <tags>
        <tag>php</tag>
      </tags>
  </entry>
  <entry>
    <title>rabbitmq-tips</title>
    <url>/2017/04/25/rabbitmq-tips/</url>
    <content><![CDATA[<h2 id="rabbitmq-介绍"><a href="#rabbitmq-介绍" class="headerlink" title="rabbitmq 介绍"></a>rabbitmq 介绍</h2><p>接触了一下rabbitmq，原来在选型的时候是在rabbitmq跟kafka之间做选择，网上搜了一下之后发现kafka的优势在于吞吐量，而rabbitmq相对注重可靠性，因为应用在im上，需要保证消息不能丢失所以就暂时选定rabbitmq，<br>Message Queue的需求由来已久，80年代最早在金融交易中，高盛等公司采用Teknekron公司的产品，当时的Message queuing软件叫做：the information bus（TIB）。 TIB被电信和通讯公司采用，路透社收购了Teknekron公司。之后，IBM开发了MQSeries，微软开发了Microsoft Message Queue（MSMQ）。这些商业MQ供应商的问题是厂商锁定，价格高昂。2001年，Java Message queuing试图解决锁定和交互性的问题，但对应用来说反而更加麻烦了。<br>RabbitMQ采用Erlang语言开发。Erlang语言由Ericson设计，专门为开发concurrent和distribution系统的一种语言，在电信领域使用广泛。OTP（Open Telecom Platform）作为Erlang语言的一部分，包含了很多基于Erlang开发的中间件／库／工具，如mnesia／SASL，极大方便了Erlang应用的开发。OTP就类似于Python语言中众多的module，用户借助这些module可以很方便的开发应用。<br>于是2004年，摩根大通和iMatrix开始着手<a href="https://en.wikipedia.org/wiki/Advanced_Message_Queuing_Protocol">Advanced Message Queuing Protocol （AMQP）</a>开放标准的开发。2006年，AMQP规范发布。2007年，Rabbit技术公司基于AMQP标准开发的RabbitMQ 1.0 发布。所有主要的编程语言均有与代理接口通讯的客户端库。</p>
<h2 id="简单的使用经验"><a href="#简单的使用经验" class="headerlink" title="简单的使用经验"></a>简单的使用经验</h2><h3 id="通俗的理解"><a href="#通俗的理解" class="headerlink" title="通俗的理解"></a>通俗的理解</h3><p>这里介绍下其中的一些概念，connection表示和队列服务器的连接，一般情况下是tcp连接， channel表示通道，可以在一个连接上建立多个通道，这里主要是节省了tcp连接握手的成本，exchange可以理解成一个路由器，将消息推送给对应的队列queue，其实是像一个订阅的模式。</p>
<h3 id="集群经验"><a href="#集群经验" class="headerlink" title="集群经验"></a>集群经验</h3><p><code>rabbitmqctl stop</code>这个是关闭rabbitmq，在搭建集群时候先关闭服务，然后使用<code>rabbitmq-server -detached</code>静默启动，这时候使用<code>rabbitmqctl cluster_status</code>查看集群状态，因为还没将节点加入集群，所以只能看到类似</p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell">Cluster status of node rabbit@rabbit1 ...
[&#123;nodes,[&#123;disc,[rabbit@rabbit1,rabbit@rabbit2,rabbit@rabbit3]&#125;]&#125;,
 &#123;running_nodes,[rabbit@rabbit2,rabbit@rabbit1]&#125;]
...done.<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>然后就可以把当前节点加入集群，</p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell">rabbit2$ rabbitmqctl stop_app #这个stop_app与stop的区别是前者停的是rabbitmq应用，保留erlang节点，
                              #后者是停止了rabbitmq和erlang节点
Stopping node rabbit@rabbit2 ...done.
rabbit2$ rabbitmqctl join_cluster rabbit@rabbit1 #这里可以用--ram指定将当前节点作为内存节点加入集群
Clustering node rabbit@rabbit2 with [rabbit@rabbit1] ...done.
rabbit2$ rabbitmqctl start_app
Starting node rabbit@rabbit2 ...done.<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>其他可以参考<a href="http://www.rabbitmq.com/clustering.html">官方文档</a></p>
<h2 id="一些坑"><a href="#一些坑" class="headerlink" title="一些坑"></a>一些坑</h2><h3 id="消息丢失"><a href="#消息丢失" class="headerlink" title="消息丢失"></a>消息丢失</h3><p>这里碰到过一个坑，对于使用exchange来做消息路由的，会有一个情况，就是在routing_key没被订阅的时候，会将该条找不到路由对应的queue的消息丢掉<code>What happens if we break our contract and send a message with one or four words, like &quot;orange&quot; or &quot;quick.orange.male.rabbit&quot;? Well, these messages won&#39;t match any bindings and will be lost.</code><a href="http://www.rabbitmq.com/tutorials/tutorial-five-python.html">对应链接</a>,而当使用空的exchange时，会保留消息，当出现消费者的时候就可以将收到之前生产者所推送的消息<a href="http://www.rabbitmq.com/tutorials/tutorial-two-python.html">对应链接</a>,这里就是用了空的exchange。</p>
<h3 id="集群搭建"><a href="#集群搭建" class="headerlink" title="集群搭建"></a>集群搭建</h3><p>集群搭建的时候有个erlang vm生成的random cookie，这个是用来做集群之间认证的，相同的cookie才能连接，但是如果通过vim打开复制后在其他几点新建文件写入会多一个换行，导致集群建立是报错，所以这里最好使用scp等传输命令直接传输cookie文件，同时要注意下cookie的文件权限。<br>另外在集群搭建的时候如果更改过hostname，那么要把rabbitmq的数据库删除，否则启动后会马上挂掉</p>
]]></content>
      <categories>
        <category>php</category>
      </categories>
      <tags>
        <tag>php</tag>
        <tag>mq</tag>
        <tag>im</tag>
      </tags>
  </entry>
  <entry>
    <title>redis 的 rdb 和 COW 介绍</title>
    <url>/2021/08/15/redis-%E7%9A%84-rdb-%E5%92%8C-COW-%E4%BB%8B%E7%BB%8D/</url>
    <content><![CDATA[<p>redis 在使用 rdb 策略进行备份时，rdb 的意思是会在开启备份的时候将开启时间点的内存数据进行备份，并且可以设置时间，这样子就是这个策略其实还是不完全可靠的，如果是在这个间隔中宕机了，或者间隔过长，不过这个不在这次的要说的内容中，如果自己去写这个 rdb 的策略可能就有点类似于 mvcc 的 redolog，需要知道这个时间点之前的数据是怎么样的，防止后面更改的干扰，但是这样一方面需要有比较复杂的 mvcc 实现，另一方面是很占用存储空间，所以 redis 在这里面使用了 COW (Copy On Write) 技术，这个技术呢以前听过，也大致了解是怎么个意思，这次稍微具体地来看下，其实 redis 的 copy-on-write 就是来自于 linux 的 cow</p>
<h3 id="Linux中的CopyOnWrite"><a href="#Linux中的CopyOnWrite" class="headerlink" title="Linux中的CopyOnWrite"></a>Linux中的CopyOnWrite</h3><p>fork()之后，kernel把父进程中所有的内存页的权限都设为read-only，然后子进程的地址空间指向父进程。当父子进程都只读内存时，相安无事。当其中某个进程写内存时，CPU硬件检测到内存页是read-only的，于是触发页异常中断（page-fault），陷入kernel的一个中断例程。中断例程中，kernel就会把触发的异常的页复制一份，于是父子进程各自持有独立的一份。这个操作其实可以类比为写屏障，正常的读取是没问题的，当有写入时就会分裂。</p>
<h3 id="CopyOnWrite的好处："><a href="#CopyOnWrite的好处：" class="headerlink" title="CopyOnWrite的好处："></a>CopyOnWrite的好处：</h3><p>1、减少分配和复制资源时带来的瞬时延迟；<br>2、减少不必要的资源分配；<br>CopyOnWrite的缺点：<br>1、如果父子进程都需要进行大量的写操作，会产生大量的分页错误（页异常中断page-fault）;</p>
<h3 id="Redis中的CopyOnWrite"><a href="#Redis中的CopyOnWrite" class="headerlink" title="Redis中的CopyOnWrite"></a>Redis中的CopyOnWrite</h3><p>Redis在持久化时，如果是采用BGSAVE命令或者BGREWRITEAOF的方式，那Redis会fork出一个子进程来读取数据，从而写到磁盘中。<br>总体来看，Redis还是读操作比较多。如果子进程存在期间，发生了大量的写操作，那可能就会出现很多的分页错误(页异常中断page-fault)，这样就得耗费不少性能在复制上。<br>而在rehash阶段上，写操作是无法避免的。所以Redis在fork出子进程之后，将负载因子阈值提高，尽量减少写操作，避免不必要的内存写入操作，最大限度地节约内存。这里其实更巧妙了，在细节上去优化会产生大量页异常中断的情况。</p>
]]></content>
      <categories>
        <category>redis</category>
      </categories>
      <tags>
        <tag>redis</tag>
      </tags>
  </entry>
  <entry>
    <title>redis数据结构介绍-第一部分 SDS，链表，字典</title>
    <url>/2019/12/26/redis%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%BB%8B%E7%BB%8D/</url>
    <content><![CDATA[<p>redis是现在服务端很常用的缓存中间件，其实原来还有<code>memcache</code>之类的竞品，但是现在貌似 redis 快一统江湖，这里当然不是在吹，只是个人角度的一个感觉，不权威只是主观感觉。<br>redis 主要有五种数据结构，<code>Strings</code>，<code>Lists</code>，<code>Sets</code>，<code>Hashes</code>，<code>Sorted Sets</code>，这五种数据结构先简单介绍下，<code>Strings</code>类型的其实就是我们最常用的 key-value，实际开发中也会用的最多；<code>Lists</code>是列表，这个有些会用来做队列，因为 redis 目前常用的版本支持丰富的列表操作；还有是<code>Sets</code>集合，这个主要的特点就是集合中元素不重复，可以用在有这类需求的场景里；<code>Hashes</code>是叫散列，类似于 Python 中的字典结构；还有就是<code>Sorted Sets</code>这个是个有序集合；一眼看这些其实没啥特别的，除了最后这个有序集合，不过去了解背后的实现方式还是比较有意思的。</p>
<h2 id="SDS-简单动态字符串"><a href="#SDS-简单动态字符串" class="headerlink" title="SDS 简单动态字符串"></a>SDS 简单动态字符串</h2><p>先从<code>Strings</code>开始说，了解过 C 语言的应该知道，C 语言中的字符串其实是个 <code>char[]</code> 字符数组，redis 也不例外，只是最开始的版本就对这个做了一丢丢的优化，而正是这一丢丢的优化，让这个 redis 的使用效率提升了数倍</p>
<pre class="line-numbers language-C" data-language="C"><code class="language-C">struct sdshdr &#123;
    &#x2F;&#x2F; 字符串长度
    int len;
    &#x2F;&#x2F; 字符串空余字符数
    int free;
    &#x2F;&#x2F; 字符串内容
    char buf[];
&#125;;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这里引用了 redis 在 github 上最早的 2.2 版本的代码，代码路径是<code>https://github.com/antirez/redis/blob/2.2/src/sds.h</code>,可以看到这个结构体里只有仨元素，两个 int 型和一个 char 型数组，两个 int 型其实就是我说的优化，因为 C 语言本身的字符串数组，有两个问题，一个是要知道它实际已被占用的长度，需要去遍历这个数组，第二个就是比较容易踩坑的是遍历的时候要注意它有个以<code>\0</code>作为结尾的特点；通过上面的两个 int 型参数，一个是知道字符串目前的长度，一个是知道字符串还剩余多少位空间，这样子坐着两个操作从 <code>O(N)</code>简化到了<code>O(1)</code>了，还有第二个 free 还有个比较重要的作用就是能防止 C 字符串的溢出问题，在存储之前可以先判断 free 长度，如果长度不够就先扩容了，先介绍到这，这个系列可以写蛮多的，慢慢介绍吧</p>
<h2 id="链表"><a href="#链表" class="headerlink" title="链表"></a>链表</h2><p>链表是比较常见的数据结构了，但是因为 redis 是用 C 写的，所以在不依赖第三方库的情况下只能自己写一个了，redis 的链表是个有头的链表，而且是无环的，具体的结构我也找了 github 上最早版本的代码</p>
<pre class="line-numbers language-C" data-language="C"><code class="language-C">typedef struct listNode &#123;
    &#x2F;&#x2F; 前置节点
    struct listNode *prev;
    &#x2F;&#x2F; 后置节点
    struct listNode *next;
    &#x2F;&#x2F; 值
    void *value;
&#125; listNode;

typedef struct list &#123;
    &#x2F;&#x2F; 链表表头
    listNode *head;
    &#x2F;&#x2F; 当前节点，也可以说是最后节点
    listNode *tail;
    &#x2F;&#x2F; 节点复制函数
    void *(*dup)(void *ptr);
    &#x2F;&#x2F; 节点值释放函数
    void (*free)(void *ptr);
    &#x2F;&#x2F; 节点值比较函数
    int (*match)(void *ptr, void *key);
    &#x2F;&#x2F; 链表包含的节点数量
    unsigned int len;
&#125; list;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>代码地址是这个<code>https://github.com/antirez/redis/blob/2.2/src/adlist.h</code><br>可以看下节点是由listNode承载的，包括值和一个指向前节点跟一个指向后一节点的两个指针，然后值是 void 指针类型，所以可以承载不同类型的值<br>然后是 list结构用来承载一个链表，包含了表头，和表尾，复制函数，释放函数和比较函数，还有链表长度，因为包含了前两个节点，找到表尾节点跟表头都是 <code>O(1)</code>的时间复杂度，还有节点数量，其实这个跟 SDS 是同一个做法，就是空间换时间，这也是写代码里比较常见的做法，以此让一些高频的操作提速。</p>
<h2 id="字典"><a href="#字典" class="headerlink" title="字典"></a>字典</h2><p>字典也是个常用的数据结构，其实只是叫法不同，数据结构中叫 hash 散列，Java 中叫 Map，PHP 中是数组 array，Python 中也叫字典 dict，因为纯 C 语言本身不带这些数据结构，所以这也是个痛并快乐着的过程，享受 C 语言的高性能的同时也要接受它只提供了语言的基本功能的现实，各种轮子都需要自己造，redis 同样实现了自己的字典<br>下面来看看代码</p>
<pre class="line-numbers language-C" data-language="C"><code class="language-C">typedef struct dictEntry &#123;
    void *key;
    void *val;
    struct dictEntry *next;
&#125; dictEntry;

typedef struct dictType &#123;
    unsigned int (*hashFunction)(const void *key);
    void *(*keyDup)(void *privdata, const void *key);
    void *(*valDup)(void *privdata, const void *obj);
    int (*keyCompare)(void *privdata, const void *key1, const void *key2);
    void (*keyDestructor)(void *privdata, void *key);
    void (*valDestructor)(void *privdata, void *obj);
&#125; dictType;

&#x2F;* This is our hash table structure. Every dictionary has two of this as we
 * implement incremental rehashing, for the old to the new table. *&#x2F;
typedef struct dictht &#123;
    dictEntry **table;
    unsigned long size;
    unsigned long sizemask;
    unsigned long used;
&#125; dictht;

typedef struct dict &#123;
    dictType *type;
    void *privdata;
    dictht ht[2];
    int rehashidx; &#x2F;* rehashing not in progress if rehashidx &#x3D;&#x3D; -1 *&#x2F;
    int iterators; &#x2F;* number of iterators currently running *&#x2F;
&#125; dict;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>看了下这个 2.2 版本的代码跟最新版的其实也差的不是很多，所以还是照旧用老代码，可以看到上面四个结构体中，其实只有三个是存储数据用的，dictType 是用来放操作函数的，那么三个存放数据的结构体分别是干嘛的，这时候感觉需要一个图来说明比较好，稍等，我去画个图~<br><img data-src="https://i.loli.net/2019/12/29/UL4AR1HSEKOh9Qm.png"><br>这个图看着应该比较清楚这些都是用来干嘛的了，dict 是我们的主体结构，它有一个指向 dictType 的指针，这里面包含了字典的操作函数，然后是一个私有数据指针，接下来是一个 dictht 的数组，包含两个dictht，这个就是用来存数据的了，然后是 rehashidx 表示重哈希的状态，当是-1 的时候表示当前没有重哈希，iterators 表示正在遍历的迭代器的数量。<br>首先说说为啥需要有两个 dictht，这是因为字典 dict 这个数据结构随着数据量的增减，会需要在中途做扩容或者缩容操作，如果只有一个的话，对它进行扩容缩容时会影响正常的访问和修改操作，或者说保证正常查询，修改的正确性会比较复杂，并且因为需要高效利用空间，不能一下子申请一个非常大的空间来存很少的数据。当 dict 中 dictht 中的数据量超过 size 的时候负载就超过了 1，就需要进行扩容，这里的其实跟 Java 中的 HashMap 比较类似，超过一定的负载之后进行扩容。这里为啥 size 会超过 1 呢，可能有部分不了解这类结构的同学会比较奇怪，其实就是上图中画的，在数据结构中对于散列的冲突有几类解决方法，比如转换成链表，二次散列，找下个空槽等，这里就使用了链表法，或者说拉链法。当一个新元素通过 hashFunction 得出的 key 跟 sizemask 取模之后的值相同了，那就将其放在原来的节点之前，变成链表挂在数组 dictht.table下面，放在原有节点前是考虑到可能会优先访问。<br>忘了说明下 dictht 跟 dictEntry 的关系了，dictht 就是个哈希表，它里面是个dictEntry 的二维数组，而 dictEntry 是个包含了 key-value 结构之外还有一个 next 指针，因此可以将哈希冲突的以链表的形式保存下来。<br>在重点说下重哈希，可能同样写 Java 的同学对这个比较有感觉，跟 HashMap 一样，会以 2 的 N 次方进行扩容，那么扩容的方法就会比较简单，每个键重哈希要不就在原来这个槽，要不就在原来的槽加原 dictht.size 的位置；然后是重头戏，具体是怎么做扩容呢，其实这里就把第二个 ht 用上了，其实这两个hashtable 的具体作用有点类似于 jvm 中的两个 survival 区，但是又不全一样，因为 redis 在扩容的时候是采用的渐进式地重哈希，什么叫渐进式的呢，就是它不是像 jvm 那种标记复制的模式直接将一个 eden 区和原来的 survival 区存活的对象复制到另一个 survival 区，而是在每一次添加，删除，查找或者更新操作时，都会额外的帮忙搬运一部分的原 dictht 中的数据，这里会根据 rehashidx 的值来判断，如果是-1 表示并没有在重哈希中，如果是 0 表示开始重哈希了，然后rehashidx 还会随着每次的帮忙搬运往上加，但全部被搬运完成后 rehashidx 又变回了-1，又可以扯到Java 中的 Concurrent HashMap, 他在扩容的时候也使用了类似的操作。</p>
]]></content>
      <categories>
        <category>Redis</category>
        <category>数据结构</category>
        <category>C</category>
        <category>源码</category>
        <category>Redis</category>
      </categories>
      <tags>
        <tag>redis</tag>
        <tag>数据结构</tag>
        <tag>源码</tag>
      </tags>
  </entry>
  <entry>
    <title>redis数据结构介绍三-第三部分 整数集合</title>
    <url>/2020/01/10/redis%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%BB%8B%E7%BB%8D%E4%B8%89/</url>
    <content><![CDATA[<p>redis中对于 set 其实有两种处理，对于元素均为整型，并且元素数目较少时，使用 intset 作为底层数据结构，否则使用 dict 作为底层数据结构，先看一下代码先</p>
<pre class="line-numbers language-C" data-language="C"><code class="language-C">typedef struct intset &#123;
    &#x2F;&#x2F; 编码方式
    uint32_t encoding;
    &#x2F;&#x2F; 集合包含的元素数量
    uint32_t length;
    &#x2F;&#x2F; 保存元素的数组
    int8_t contents[];
&#125; intset;

&#x2F;* Note that these encodings are ordered, so:
 * INTSET_ENC_INT16 &lt; INTSET_ENC_INT32 &lt; INTSET_ENC_INT64. *&#x2F;
#define INTSET_ENC_INT16 (sizeof(int16_t))
#define INTSET_ENC_INT32 (sizeof(int32_t))
#define INTSET_ENC_INT64 (sizeof(int64_t))<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>一眼看，为啥整型还需要编码，然后 int8_t 怎么能存下大整形呢，带着这些疑问，我们一步步分析下去，这里的编码其实指的是这个整型集合里存的究竟是多大的整型，16 位，还是 32 位，还是 64 位，结构体下面的宏定义就是表示了 encoding 的可能取值，INTSET_ENC_INT16 表示每个元素用2个字节存储，INTSET_ENC_INT32 表示每个元素用4个字节存储，INTSET_ENC_INT64 表示每个元素用8个字节存储。因此，intset中存储的整数最多只能占用64bit。length 就是正常的表示集合中元素的数量。最奇怪的应该就是这个 contents 了，是个 int8_t 的数组，那放毛线数据啊，最小的都有 16 位，这里我在看代码和《redis 设计与实现》的时候也有点懵逼，后来查了下发现这是个比较取巧的用法，这里我用自己的理解表述一下，先看看 8，16，32，64 的关系，一眼看就知道都是 2 的 N 次，并且呈两倍关系，而且 8 位刚好一个字节，所以呢其实这里的contents 不是个常规意义上的 int8_t 类型的数组，而是个柔性数组。看下 wiki 的定义</p>
<blockquote>
<p>Flexible array members<a href="https://en.wikipedia.org/wiki/Flexible_array_member#cite_note-1">1</a> were introduced in the <a href="https://en.wikipedia.org/wiki/C99">C99</a> standard of the <a href="https://en.wikipedia.org/wiki/C_(programming_language)">C programming language</a> (in particular, in section §6.7.2.1, item 16, page 103).<a href="https://en.wikipedia.org/wiki/Flexible_array_member#cite_note-2">2</a> It is a member of a struct, which is an array without a given dimension. It must be the last member of such a struct and it must be accompanied by at least one other member, as in the following example:</p>
</blockquote>
<pre class="line-numbers language-C" data-language="C"><code class="language-C">struct vectord &#123;
    size_t len;
    double arr[]; &#x2F;&#x2F; the flexible array member must be last
&#125;;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>在初始化这个 intset 的时候，这个contents数组是不占用空间的，后面的反正用到了申请，那么这里就有一个问题，给出了三种可能的 encoding 值，他们能随便换吗，显然不行，首先在 intset 中数据的存放是有序的，这个有部分原因是方便二分查找，然后存放数据其实随着数据的大小不同会有一个升级的过程，看下图<br><img data-src="https://i.loli.net/2020/01/10/qIc6HgP7wfCLipN.png"><br>新创建的intset只有一个header，总共8个字节。其中encoding = 2, length = 0, 类型都是uint32_t，各占 4 字节，添加15, 5两个元素之后，因为它们是比较小的整数，都能使用2个字节表示，所以encoding不变，值还是2，也就是默认的 <code>INTSET_ENC_INT16</code>，当添加32768的时候，它不再能用2个字节来表示了（2个字节能表达的数据范围是-215~215-1，而32768等于215，超出范围了），因此encoding必须升级到INTSET_ENC_INT32（值为4），即用4个字节表示一个元素。在添加每个元素的过程中，intset始终保持从小到大有序。与ziplist类似，intset也是按小端（little endian）模式存储的（参见维基百科词条<a href="https://en.wikipedia.org/wiki/Endianness">Endianness</a>）。比如，在上图中intset添加完所有数据之后，表示encoding字段的4个字节应该解释成0x00000004，而第4个数据应该解释成0x00008000 = 32768</p>
]]></content>
      <categories>
        <category>Redis</category>
        <category>数据结构</category>
        <category>C</category>
        <category>源码</category>
        <category>Redis</category>
      </categories>
      <tags>
        <tag>redis</tag>
        <tag>数据结构</tag>
        <tag>源码</tag>
      </tags>
  </entry>
  <entry>
    <title>redis数据结构介绍二-第二部分 跳表</title>
    <url>/2020/01/04/redis%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%BB%8B%E7%BB%8D%E4%BA%8C/</url>
    <content><![CDATA[<h2 id="跳表-skiplist"><a href="#跳表-skiplist" class="headerlink" title="跳表 skiplist"></a>跳表 skiplist</h2><p>跳表是个在我们日常的代码中不太常用到的数据结构，相对来讲就没有像数组，链表，字典，散列，树等结构那么熟悉，所以就从头开始分析下，首先是链表，跳表跟链表都有个表字（太硬扯了我🤦‍♀️），注意这是个有序链表<br><img data-src="https://i.loli.net/2020/01/03/Og9i3pCIfxrMhja.png"><br>如上图，在这个链表里如果我要找到 23，是不是我需要从3，5，9开始一直往后找直到找到 23，也就是说时间复杂度是 O(N),N 的一次幂复杂度，那么我们来看看第二个<br><img data-src="https://i.loli.net/2020/01/03/81P2baupiedOmNf.png"><br>这个结构跟原先有点不一样，它给链表中偶数位的节点又加了一个指针把它们链接起来，这样子当我们要寻找 23 的时候就可以从原来的一个个往下找变成跳着找，先找到 5，然后是 10，接着是 19，然后是 28，这时候发现 28 比 23 大了，那我在退回到 19，然后从下一层原来的链表往前找，<br><img data-src="https://i.loli.net/2020/01/03/NBguAphilKjs2MO.png"><br>这里毛估估是不是前面的节点我就少找了一半,有那么点二分法的意思。<br>前面的其实是跳表的引子，真正的跳表其实不是这样，因为上面的其实有个比较大的问题，就是插入一个元素后需要调整每个元素的指针，在 redis 中的跳表其实是做了个随机层数的优化，因为沿着前面的例子，其实当数据量很大的时候，是不是层数越多，其查询效率越高，但是随着层数变多，要保持这种严格的层数规则其实也会增大处理复杂度，所以 redis 插入每个元素的时候都是使用随机的方式，看一眼代码</p>
<pre class="line-numbers language-C" data-language="C"><code class="language-C">&#x2F;* ZSETs use a specialized version of Skiplists *&#x2F;
typedef struct zskiplistNode &#123;
    sds ele;
    double score;
    struct zskiplistNode *backward;
    struct zskiplistLevel &#123;
        struct zskiplistNode *forward;
        unsigned long span;
    &#125; level[];
&#125; zskiplistNode;

typedef struct zskiplist &#123;
    struct zskiplistNode *header, *tail;
    unsigned long length;
    int level;
&#125; zskiplist;

typedef struct zset &#123;
    dict *dict;
    zskiplist *zsl;
&#125; zset;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>忘了说了，redis 是把 skiplist 跳表用在 zset 里，zset 是个有序的集合，可以看到 zskiplist 就是个跳表的结构，里面用 header 保存跳表的表头，tail 保存表尾，还有长度和最大层级，具体的跳表节点元素使用 zskiplistNode 表示，里面包含了 sds 类型的元素值，double 类型的分值，用来排序，一个 backward 后向指针和一个 zskiplistLevel 数组，每个 level 包含了一个前向指针，和一个 span，span 表示的是跳表前向指针的跨度，这里再补充一点，前面说了为了灵活这个跳表的新增修改，redis 使用了随机层高的方式插入新节点，但是如果所有节点都随机到很高的层级或者所有都很低的话，跳表的效率优势就会减小，所以 redis 使用了个小技巧，贴下代码</p>
<pre class="line-numbers language-C" data-language="C"><code class="language-C">#define ZSKIPLIST_P 0.25      &#x2F;* Skiplist P &#x3D; 1&#x2F;4 *&#x2F;
int zslRandomLevel(void) &#123;
    int level &#x3D; 1;
    while ((random()&amp;0xFFFF) &lt; (ZSKIPLIST_P * 0xFFFF))
        level +&#x3D; 1;
    return (level&lt;ZSKIPLIST_MAXLEVEL) ? level : ZSKIPLIST_MAXLEVEL;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>当随机值跟0xFFFF进行与操作小于ZSKIPLIST_P * 0xFFFF时才会增大 level 的值，因此保持了一个相对递减的概率<br>可以简单分析下，当 random() 的值小于 0xFFFF 的 1/4,才会 level + 1，就意味着当有 1 - 1/4也就是3/4的概率是直接跳出，所以一层的概率是3/4,也就是 1-P，二层的概率是 P*(1-P),三层的概率是 P² * (1-P) 依次递推。</p>
]]></content>
      <categories>
        <category>Redis</category>
        <category>数据结构</category>
        <category>C</category>
        <category>源码</category>
        <category>Redis</category>
      </categories>
      <tags>
        <tag>redis</tag>
        <tag>数据结构</tag>
        <tag>源码</tag>
      </tags>
  </entry>
  <entry>
    <title>redis数据结构介绍五-第五部分 对象</title>
    <url>/2020/01/20/redis%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%BB%8B%E7%BB%8D%E4%BA%94/</url>
    <content><![CDATA[<p>前面说了这么些数据结构，其实大家对于 redis 最初的印象应该就是个 key-value 的缓存，类似于 memcache，redis 其实也是个 key-value，key 还是一样的字符串，或者说就是用 redis 自己的动态字符串实现，但是 value 其实就是前面说的那些数据结构，差不多快说完了，还有个 quicklist 后面还有一篇，这里先介绍下 redis 对于这些不同类型的 value 是怎么实现的，首先看下 redisObject 的源码头文件</p>
<pre class="line-numbers language-C" data-language="C"><code class="language-C">&#x2F;* The actual Redis Object *&#x2F;
#define OBJ_STRING 0    &#x2F;* String object. *&#x2F;
#define OBJ_LIST 1      &#x2F;* List object. *&#x2F;
#define OBJ_SET 2       &#x2F;* Set object. *&#x2F;
#define OBJ_ZSET 3      &#x2F;* Sorted set object. *&#x2F;
#define OBJ_HASH 4      &#x2F;* Hash object. *&#x2F;
&#x2F;*
 * Objects encoding. Some kind of objects like Strings and Hashes can be
 * internally represented in multiple ways. The &#39;encoding&#39; field of the object
 * is set to one of this fields for this object. *&#x2F;
#define OBJ_ENCODING_RAW 0     &#x2F;* Raw representation *&#x2F;
#define OBJ_ENCODING_INT 1     &#x2F;* Encoded as integer *&#x2F;
#define OBJ_ENCODING_HT 2      &#x2F;* Encoded as hash table *&#x2F;
#define OBJ_ENCODING_ZIPMAP 3  &#x2F;* Encoded as zipmap *&#x2F;
#define OBJ_ENCODING_LINKEDLIST 4 &#x2F;* No longer used: old list encoding. *&#x2F;
#define OBJ_ENCODING_ZIPLIST 5 &#x2F;* Encoded as ziplist *&#x2F;
#define OBJ_ENCODING_INTSET 6  &#x2F;* Encoded as intset *&#x2F;
#define OBJ_ENCODING_SKIPLIST 7  &#x2F;* Encoded as skiplist *&#x2F;
#define OBJ_ENCODING_EMBSTR 8  &#x2F;* Embedded sds string encoding *&#x2F;
#define OBJ_ENCODING_QUICKLIST 9 &#x2F;* Encoded as linked list of ziplists *&#x2F;
#define OBJ_ENCODING_STREAM 10 &#x2F;* Encoded as a radix tree of listpacks *&#x2F;

#define LRU_BITS 24
#define LRU_CLOCK_MAX ((1&lt;&lt;LRU_BITS)-1) &#x2F;* Max value of obj-&gt;lru *&#x2F;
#define LRU_CLOCK_RESOLUTION 1000 &#x2F;* LRU clock resolution in ms *&#x2F;

#define OBJ_SHARED_REFCOUNT INT_MAX
typedef struct redisObject &#123;
    unsigned type:4;
    unsigned encoding:4;
    unsigned lru:LRU_BITS; &#x2F;* LRU time (relative to global lru_clock) or
                            * LFU data (least significant 8 bits frequency
                            * and most significant 16 bits access time). *&#x2F;
    int refcount;
    void *ptr;
&#125; robj;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>主体结构就是这个 redisObject，</p>
<ul>
<li>type： 字段表示对象的类型，它对应的就是 redis 的对外暴露的，或者说用户可以使用的五种类型，OBJ_STRING, OBJ_LIST, OBJ_SET, OBJ_ZSET, OBJ_HASH</li>
<li>encoding： 字段表示这个对象在 redis 内部的编码方式，由OBJ_ENCODING_开头的 11 种</li>
<li>lru: 做LRU替换算法用，占24个bit</li>
<li>refcount: 引用计数。它允许robj对象在某些情况下被共享。</li>
<li>ptr: 指向底层实现数据结构的指针<br>当 type 是 OBJ_STRING 时，表示类型是个 string，它的编码方式 encoding 可能有 OBJ_ENCODING_RAW，OBJ_ENCODING_INT，OBJ_ENCODING_EMBSTR 三种<br>当 type 是 OBJ_LIST 时，表示类型是 list，它的编码方式 encoding 是 OBJ_ENCODING_QUICKLIST，对于早一些的版本，2.2这种可能还会使用 OBJ_ENCODING_ZIPLIST，OBJ_ENCODING_LINKEDLIST<br>当 type 是 OBJ_SET 时，是个集合，但是得看具体元素的类型，有可能使用整数集合，OBJ_ENCODING_INTSET, 如果元素不全是整型或者数量超过一定限制，那么编码就是 OBJ_ENCODING_HT hash table 了<br>当 type 是 OBJ_ZSET 时，是个有序集合，它底层有可能使用的是 OBJ_ENCODING_ZIPLIST 或者 OBJ_ENCODING_SKIPLIST<br>当 type 是 OBJ_HASH 时，一开始也是 OBJ_ENCODING_ZIPLIST，然后当数据量大于 hash_max_ziplist_entries 时会转成 OBJ_ENCODING_HT</li>
</ul>
]]></content>
      <categories>
        <category>Redis</category>
        <category>数据结构</category>
        <category>C</category>
        <category>源码</category>
        <category>Redis</category>
      </categories>
      <tags>
        <tag>redis</tag>
        <tag>数据结构</tag>
        <tag>源码</tag>
      </tags>
  </entry>
  <entry>
    <title>redis数据结构介绍六 快表</title>
    <url>/2020/01/22/redis%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%BB%8B%E7%BB%8D%E5%85%AD/</url>
    <content><![CDATA[<p>这应该是 redis 系列的最后一篇了，讲下快表，其实最前面讲的链表在早先的 redis 版本中也作为 list 的数据结构使用过，但是单纯的链表的缺陷之前也说了，插入便利，但是空间利用率低，并且不能进行二分查找等，检索效率低，ziplist 压缩表的产生也是同理，希望获得更好的性能，包括存储空间和访问性能等，原来我也不懂这个快表要怎么快，然后明白了一个道理，其实并没有什么银弹，只是大牛们会在适合的时候使用最适合的数据结构来实现性能的最大化，这里面有一招就是不同数据结构的组合调整，比如 Java 中的 HashMap，在链表节点数大于 8 时会转变成红黑树，以此提高访问效率，不费话了，回到快表，quicklist，这个数据结构主要使用在 list 类型中，如果我说其实这个 quicklist 就是个链表，可能大家不太会相信，但是事实上的确可以认为 quicklist 是个双向链表，看下代码</p>
<pre class="line-numbers language-C" data-language="C"><code class="language-C">&#x2F;* quicklistNode is a 32 byte struct describing a ziplist for a quicklist.
 * We use bit fields keep the quicklistNode at 32 bytes.
 * count: 16 bits, max 65536 (max zl bytes is 65k, so max count actually &lt; 32k).
 * encoding: 2 bits, RAW&#x3D;1, LZF&#x3D;2.
 * container: 2 bits, NONE&#x3D;1, ZIPLIST&#x3D;2.
 * recompress: 1 bit, bool, true if node is temporarry decompressed for usage.
 * attempted_compress: 1 bit, boolean, used for verifying during testing.
 * extra: 10 bits, free for future use; pads out the remainder of 32 bits *&#x2F;
typedef struct quicklistNode &#123;
    struct quicklistNode *prev;
    struct quicklistNode *next;
    unsigned char *zl;
    unsigned int sz;             &#x2F;* ziplist size in bytes *&#x2F;
    unsigned int count : 16;     &#x2F;* count of items in ziplist *&#x2F;
    unsigned int encoding : 2;   &#x2F;* RAW&#x3D;&#x3D;1 or LZF&#x3D;&#x3D;2 *&#x2F;
    unsigned int container : 2;  &#x2F;* NONE&#x3D;&#x3D;1 or ZIPLIST&#x3D;&#x3D;2 *&#x2F;
    unsigned int recompress : 1; &#x2F;* was this node previous compressed? *&#x2F;
    unsigned int attempted_compress : 1; &#x2F;* node can&#39;t compress; too small *&#x2F;
    unsigned int extra : 10; &#x2F;* more bits to steal for future usage *&#x2F;
&#125; quicklistNode;

&#x2F;* quicklistLZF is a 4+N byte struct holding &#39;sz&#39; followed by &#39;compressed&#39;.
 * &#39;sz&#39; is byte length of &#39;compressed&#39; field.
 * &#39;compressed&#39; is LZF data with total (compressed) length &#39;sz&#39;
 * NOTE: uncompressed length is stored in quicklistNode-&gt;sz.
 * When quicklistNode-&gt;zl is compressed, node-&gt;zl points to a quicklistLZF *&#x2F;
typedef struct quicklistLZF &#123;
    unsigned int sz; &#x2F;* LZF size in bytes*&#x2F;
    char compressed[];
&#125; quicklistLZF;

&#x2F;* quicklist is a 40 byte struct (on 64-bit systems) describing a quicklist.
 * &#39;count&#39; is the number of total entries.
 * &#39;len&#39; is the number of quicklist nodes.
 * &#39;compress&#39; is: -1 if compression disabled, otherwise it&#39;s the number
 *                of quicklistNodes to leave uncompressed at ends of quicklist.
 * &#39;fill&#39; is the user-requested (or default) fill factor. *&#x2F;
typedef struct quicklist &#123;
    quicklistNode *head;
    quicklistNode *tail;
    unsigned long count;        &#x2F;* total count of all entries in all ziplists *&#x2F;
    unsigned long len;          &#x2F;* number of quicklistNodes *&#x2F;
    int fill : 16;              &#x2F;* fill factor for individual nodes *&#x2F;
    unsigned int compress : 16; &#x2F;* depth of end nodes not to compress;0&#x3D;off *&#x2F;
&#125; quicklist;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>粗略看下，quicklist 里有 head，tail, quicklistNode里有 prev，next 指针，是不是有链表的基本轮廓了，那么为啥这玩意要称为快表呢，快在哪，关键就在这个<code>unsigned char *zl;</code>zl 是不是前面又看到过，就是 ziplist ，这是什么鬼，链表里用压缩表，这不套娃么，先别急，回顾下前面说的 ziplist，ziplist 有哪些特点，内存利用率高，可以从表头快速定位到尾节点，节点可以从后往前找，但是有个缺点，就是从中间插入的效率比较低，需要整体往后移，这个其实是普通数组的优化版，但还是有数组的一些劣势，所以要真的快，是不是可以将链表跟数组真的结合起来。</p>
<h2 id="ziplist"><a href="#ziplist" class="headerlink" title="ziplist"></a>ziplist</h2><p>这里有两个 redis 的配置参数，<code>list-max-ziplist-size</code> 和 <code>list-compress-depth</code>，先来说第一个，既然快表是将链表跟压缩表数组结合起来使用，那么具体怎么用呢，比如我有一个 10 个元素的 list，那具体怎么放，每个 quicklistNode 里放多大的 ziplist，假如每个快表节点的 ziplist 只放一个元素，那么其实这就退化成了一个链表，如果 10 个元素放在一个 quicklistNode 的 ziplist 里，那就退化成了一个 ziplist，所以有了这个 <code>list-max-ziplist-size</code>,而且它还比较牛，能取正负值，当是正值时，对应的就是每个 quicklistNode 的 ziplist 中的元素个数，比如配置了 <code>list-max-ziplist-size = 5</code>，那么我刚才的 10 个元素的 list 就是一个两个 quicklistNode 组成的快表，每个 quicklistNode 中的 ziplist 包含了五个元素，当 <code>list-max-ziplist-size</code>取负值的时候，它限制了 ziplist 的字节数</p>
<pre class="line-numbers language-none"><code class="language-none">size_t offset &#x3D; (-fill) - 1;
if (offset &lt; (sizeof(optimization_level) &#x2F; sizeof(*optimization_level))) &#123;
    if (sz &lt;&#x3D; optimization_level[offset]) &#123;
        return 1;
    &#125; else &#123;
        return 0;
    &#125;
&#125; else &#123;
    return 0;
&#125;

&#x2F;* Optimization levels for size-based filling *&#x2F;
static const size_t optimization_level[] &#x3D; &#123;4096, 8192, 16384, 32768, 65536&#125;;

&#x2F;* Create a new quicklist.
 * Free with quicklistRelease(). *&#x2F;
quicklist *quicklistCreate(void) &#123;
    struct quicklist *quicklist;

    quicklist &#x3D; zmalloc(sizeof(*quicklist));
    quicklist-&gt;head &#x3D; quicklist-&gt;tail &#x3D; NULL;
    quicklist-&gt;len &#x3D; 0;
    quicklist-&gt;count &#x3D; 0;
    quicklist-&gt;compress &#x3D; 0;
    quicklist-&gt;fill &#x3D; -2;
    return quicklist;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这个 fill 就是传进来的 <code>list-max-ziplist-size</code>, 具体对应的就是</p>
<ul>
<li>-5: 每个quicklist节点上的ziplist大小不能超过64 Kb。（注：1kb =&gt; 1024 bytes）</li>
<li>-4: 每个quicklist节点上的ziplist大小不能超过32 Kb。</li>
<li>-3: 每个quicklist节点上的ziplist大小不能超过16 Kb。</li>
<li>-2: 每个quicklist节点上的ziplist大小不能超过8 Kb。（-2是Redis给出的默认值）也就是上面的 <code>quicklist-&gt;fill = -2;</code></li>
<li>-1: 每个quicklist节点上的ziplist大小不能超过4 Kb。</li>
</ul>
<h2 id="压缩"><a href="#压缩" class="headerlink" title="压缩"></a>压缩</h2><p><code>list-compress-depth</code>这个参数呢是用来配置压缩的，等等压缩是为啥，不是里面已经是压缩表了么，大牛们就是为了性能殚精竭虑，这里考虑到的是一个场景，一般状况下，list 都是两端的访问频率比较高，那么是不是可以对中间的数据进行压缩，那么这个参数就是用来表示</p>
<pre class="line-numbers language-none"><code class="language-none">&#x2F;* depth of end nodes not to compress;0&#x3D;off *&#x2F;<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ul>
<li>0，代表不压缩，默认值</li>
<li>1，两端各一个节点不压缩</li>
<li>2，两端各两个节点不压缩</li>
<li>… 依次类推<br>压缩后的 ziplist 就会变成 quicklistLZF，然后替换 zl 指针，这里使用的是 <a href="http://oldhome.schmorp.de/marc/liblzf.html">LZF</a> 压缩算法，压缩后的 quicklistLZF 中的 compressed 也是个柔性数组，压缩后的 ziplist 整个就放进这个柔性数组</li>
</ul>
<h2 id="插入过程"><a href="#插入过程" class="headerlink" title="插入过程"></a>插入过程</h2><p>简单说下插入元素的过程</p>
<pre class="line-numbers language-none"><code class="language-none">&#x2F;* Wrapper to allow argument-based switching between HEAD&#x2F;TAIL pop *&#x2F;
void quicklistPush(quicklist *quicklist, void *value, const size_t sz,
                   int where) &#123;
    if (where &#x3D;&#x3D; QUICKLIST_HEAD) &#123;
        quicklistPushHead(quicklist, value, sz);
    &#125; else if (where &#x3D;&#x3D; QUICKLIST_TAIL) &#123;
        quicklistPushTail(quicklist, value, sz);
    &#125;
&#125;

&#x2F;* Add new entry to head node of quicklist.
 *
 * Returns 0 if used existing head.
 * Returns 1 if new head created. *&#x2F;
int quicklistPushHead(quicklist *quicklist, void *value, size_t sz) &#123;
    quicklistNode *orig_head &#x3D; quicklist-&gt;head;
    if (likely(
            _quicklistNodeAllowInsert(quicklist-&gt;head, quicklist-&gt;fill, sz))) &#123;
        quicklist-&gt;head-&gt;zl &#x3D;
            ziplistPush(quicklist-&gt;head-&gt;zl, value, sz, ZIPLIST_HEAD);
        quicklistNodeUpdateSz(quicklist-&gt;head);
    &#125; else &#123;
        quicklistNode *node &#x3D; quicklistCreateNode();
        node-&gt;zl &#x3D; ziplistPush(ziplistNew(), value, sz, ZIPLIST_HEAD);

        quicklistNodeUpdateSz(node);
        _quicklistInsertNodeBefore(quicklist, quicklist-&gt;head, node);
    &#125;
    quicklist-&gt;count++;
    quicklist-&gt;head-&gt;count++;
    return (orig_head !&#x3D; quicklist-&gt;head);
&#125;

&#x2F;* Add new entry to tail node of quicklist.
 *
 * Returns 0 if used existing tail.
 * Returns 1 if new tail created. *&#x2F;
int quicklistPushTail(quicklist *quicklist, void *value, size_t sz) &#123;
    quicklistNode *orig_tail &#x3D; quicklist-&gt;tail;
    if (likely(
            _quicklistNodeAllowInsert(quicklist-&gt;tail, quicklist-&gt;fill, sz))) &#123;
        quicklist-&gt;tail-&gt;zl &#x3D;
            ziplistPush(quicklist-&gt;tail-&gt;zl, value, sz, ZIPLIST_TAIL);
        quicklistNodeUpdateSz(quicklist-&gt;tail);
    &#125; else &#123;
        quicklistNode *node &#x3D; quicklistCreateNode();
        node-&gt;zl &#x3D; ziplistPush(ziplistNew(), value, sz, ZIPLIST_TAIL);

        quicklistNodeUpdateSz(node);
        _quicklistInsertNodeAfter(quicklist, quicklist-&gt;tail, node);
    &#125;
    quicklist-&gt;count++;
    quicklist-&gt;tail-&gt;count++;
    return (orig_tail !&#x3D; quicklist-&gt;tail);
&#125;

&#x2F;* Wrappers for node inserting around existing node. *&#x2F;
REDIS_STATIC void _quicklistInsertNodeBefore(quicklist *quicklist,
                                             quicklistNode *old_node,
                                             quicklistNode *new_node) &#123;
    __quicklistInsertNode(quicklist, old_node, new_node, 0);
&#125;

REDIS_STATIC void _quicklistInsertNodeAfter(quicklist *quicklist,
                                            quicklistNode *old_node,
                                            quicklistNode *new_node) &#123;
    __quicklistInsertNode(quicklist, old_node, new_node, 1);
&#125;

&#x2F;* Insert &#39;new_node&#39; after &#39;old_node&#39; if &#39;after&#39; is 1.
 * Insert &#39;new_node&#39; before &#39;old_node&#39; if &#39;after&#39; is 0.
 * Note: &#39;new_node&#39; is *always* uncompressed, so if we assign it to
 *       head or tail, we do not need to uncompress it. *&#x2F;
REDIS_STATIC void __quicklistInsertNode(quicklist *quicklist,
                                        quicklistNode *old_node,
                                        quicklistNode *new_node, int after) &#123;
    if (after) &#123;
        new_node-&gt;prev &#x3D; old_node;
        if (old_node) &#123;
            new_node-&gt;next &#x3D; old_node-&gt;next;
            if (old_node-&gt;next)
                old_node-&gt;next-&gt;prev &#x3D; new_node;
            old_node-&gt;next &#x3D; new_node;
        &#125;
        if (quicklist-&gt;tail &#x3D;&#x3D; old_node)
            quicklist-&gt;tail &#x3D; new_node;
    &#125; else &#123;
        new_node-&gt;next &#x3D; old_node;
        if (old_node) &#123;
            new_node-&gt;prev &#x3D; old_node-&gt;prev;
            if (old_node-&gt;prev)
                old_node-&gt;prev-&gt;next &#x3D; new_node;
            old_node-&gt;prev &#x3D; new_node;
        &#125;
        if (quicklist-&gt;head &#x3D;&#x3D; old_node)
            quicklist-&gt;head &#x3D; new_node;
    &#125;
    &#x2F;* If this insert creates the only element so far, initialize head&#x2F;tail. *&#x2F;
    if (quicklist-&gt;len &#x3D;&#x3D; 0) &#123;
        quicklist-&gt;head &#x3D; quicklist-&gt;tail &#x3D; new_node;
    &#125;

    if (old_node)
        quicklistCompress(quicklist, old_node);

    quicklist-&gt;len++;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>前面第一步先根据插入的是头还是尾选择不同的 push 函数，quicklistPushHead 或者 quicklistPushTail，举例分析下从头插入的 quicklistPushHead，先判断当前的 quicklistNode 节点还能不能允许再往 ziplist 里添加元素，如果可以就添加，如果不允许就新建一个 quicklistNode，然后调用 _quicklistInsertNodeBefore 将节点插进去，具体插入quicklist节点的操作类似链表的插入。</p>
]]></content>
      <categories>
        <category>Redis</category>
        <category>数据结构</category>
        <category>C</category>
        <category>源码</category>
        <category>Redis</category>
      </categories>
      <tags>
        <tag>redis</tag>
        <tag>数据结构</tag>
        <tag>源码</tag>
      </tags>
  </entry>
  <entry>
    <title>redis数据结构介绍四-第四部分 压缩表</title>
    <url>/2020/01/19/redis%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%BB%8B%E7%BB%8D%E5%9B%9B/</url>
    <content><![CDATA[<p>在 redis 中还有一类表型数据结构叫压缩表，ziplist，它的目的是替代链表，链表是个很容易理解的数据结构，双向链表有前后指针，有带头结点的有的不带，但是链表有个比较大的问题是相对于普通的数组，它的内存不连续，碎片化的存储，内存利用效率不高，而且指针寻址相对于直接使用偏移量的话，也有一定的效率劣势，当然这不是主要的原因，ziplist 设计的主要目的是让链表的内存使用更高效</p>
<blockquote>
<p>The ziplist is a specially encoded dually linked list that is designed to be very memory efficient.<br>这是摘自 redis 源码中ziplist.c 文件的注释，也说明了原因，它的大概结构是这样子</p>
</blockquote>
<pre class="line-numbers language-none"><code class="language-none">&lt;zlbytes&gt; &lt;zltail&gt; &lt;zllen&gt; &lt;entry&gt; &lt;entry&gt; ... &lt;entry&gt; &lt;zlend&gt;<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>其中<br><code>&lt;zlbytes&gt;</code>表示 ziplist 占用的字节总数，类型是uint32_t，32 位的无符号整型，当然表示的字节数也包含自己本身占用的 4 个<br><code>&lt;zltail&gt;</code> 类型也是是uint32_t，表示ziplist表中最后一项（entry）在ziplist中的偏移字节数。<code>&lt;zltail&gt;</code>的存在，使得我们可以很方便地找到最后一项（不用遍历整个ziplist），从而可以在ziplist尾端快速地执行push或pop操作。<br><code>&lt;uint16_t zllen&gt;</code> 表示ziplist 中的数据项个数，因为是 16 位，所以当数量超过所能表示的最大的数量，它的 16 位全会置为 1，但是真实的数量需要遍历整个 ziplist 才能知道<br><code>&lt;entry&gt;</code>是具体的数据项，后面解释<br><code>&lt;zlend&gt;</code> ziplist 的最后一个字节，固定是255。<br>再看一下<code>&lt;entry&gt;</code>中的具体结构，</p>
<pre class="line-numbers language-none"><code class="language-none">&lt;prevlen&gt; &lt;encoding&gt; &lt;entry-data&gt;<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>首先这个<code>&lt;prevlen&gt;</code>有两种情况，一种是前面的元素的长度，如果是小于等于 253的时候就用一个uint8_t 来表示前一元素的长度，如果大于的话他将占用五个字节，第一个字节是 254，即表示这个字节已经表示不下了，需要后面的四个字节帮忙表示<br><code>&lt;encoding&gt;</code>这个就比较复杂，把源码的注释放下面先看下</p>
<pre class="line-numbers language-none"><code class="language-none">* |00pppppp| - 1 byte
*      String value with length less than or equal to 63 bytes (6 bits).
*      &quot;pppppp&quot; represents the unsigned 6 bit length.
* |01pppppp|qqqqqqqq| - 2 bytes
*      String value with length less than or equal to 16383 bytes (14 bits).
*      IMPORTANT: The 14 bit number is stored in big endian.
* |10000000|qqqqqqqq|rrrrrrrr|ssssssss|tttttttt| - 5 bytes
*      String value with length greater than or equal to 16384 bytes.
*      Only the 4 bytes following the first byte represents the length
*      up to 32^2-1. The 6 lower bits of the first byte are not used and
*      are set to zero.
*      IMPORTANT: The 32 bit number is stored in big endian.
* |11000000| - 3 bytes
*      Integer encoded as int16_t (2 bytes).
* |11010000| - 5 bytes
*      Integer encoded as int32_t (4 bytes).
* |11100000| - 9 bytes
*      Integer encoded as int64_t (8 bytes).
* |11110000| - 4 bytes
*      Integer encoded as 24 bit signed (3 bytes).
* |11111110| - 2 bytes
*      Integer encoded as 8 bit signed (1 byte).
* |1111xxxx| - (with xxxx between 0000 and 1101) immediate 4 bit integer.
*      Unsigned integer from 0 to 12. The encoded value is actually from
*      1 to 13 because 0000 and 1111 can not be used, so 1 should be
*      subtracted from the encoded 4 bit value to obtain the right value.
* |11111111| - End of ziplist special entry.<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>首先如果 encoding 的前两位是 00 的话代表这个元素是个 6 位的字符串，即直接将数据保存在 encoding 中，不消耗额外的<code>&lt;entry-data&gt;</code>，如果前两位是 01 的话表示是个 14 位的字符串，如果是 10 的话表示encoding 块之后的四个字节是存放字符串类型的数据，encoding 的剩余 6 位置 0。<br>如果 encoding 的前两位是 11 的话表示这是个整型，具体的如果后两位是00的话，表示后面是个2字节的 int16_t 类型，如果是01的话，后面是个4字节的int32_t,如果是10的话后面是8字节的int64_t,如果是 11 的话后面是 3 字节的有符号整型，这些都要最后 4 位都是 0 的情况噢<br>剩下当是<code>11111110</code>时，则表示是一个1 字节的有符号数，如果是 <code>1111xxxx</code>，其中<code>xxxx</code>在0000 到 1101 表示实际的 1 到 13，为啥呢，因为 0000 前面已经用过了，而 1110 跟 1111 也都有用了。<br>看个具体的例子(上下有点对不齐，将就看)</p>
<pre class="line-numbers language-none"><code class="language-none">[0f 00 00 00] [0c 00 00 00] [02 00] [00 f3] [02 f6] [ff]
|**zlbytes***|  |***zltail***|  |*zllen*|  |entry1 entry2|  |zlend|<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>第一部分代表整个 ziplist 有 15 个字节，zlbytes 自己占了 4 个 zltail 表示最后一个元素的偏移量，第 13 个字节起，zllen 表示有 2 个元素，第一个元素是<code>00f3</code>,00表示前一个元素长度是 0，本来前面就没元素(不过不知道这个能不能优化这一字节)，然后是 f3，换成二进制就是11110011,对照上面的注释，是落在|1111xxxx|这个类型里，注意这个其实是用 0001 到 1101 也就是 1到 13 来表示 0到 12，所以 f3 应该就是 2，第一个元素是 2，第二个元素呢，02 代表前一个元素也就是刚才说的这个，占用 2 字节，f6 展开也是刚才的类型，实际是 5，ff 表示 ziplist 的结尾，所以这个 ziplist 里面是两个元素，2 跟 5</p>
]]></content>
      <categories>
        <category>Redis</category>
        <category>数据结构</category>
        <category>C</category>
        <category>源码</category>
        <category>Redis</category>
      </categories>
      <tags>
        <tag>redis</tag>
        <tag>数据结构</tag>
        <tag>源码</tag>
      </tags>
  </entry>
  <entry>
    <title>redis淘汰策略复习</title>
    <url>/2021/08/01/redis%E6%B7%98%E6%B1%B0%E7%AD%96%E7%95%A5%E5%A4%8D%E4%B9%A0/</url>
    <content><![CDATA[<p>前面复习了 redis 的过期策略，这里再复习下淘汰策略，淘汰跟过期的区别有时候会被混淆了，过期主要针对那些设置了过期时间的 key，应该说是一种逻辑策略，是主动的还是被动的加定时的，两种有各自的取舍，而淘汰也可以看成是一种保持系统稳定的策略，因为如果内存满了，不采取任何策略处理，那大概率会导致系统故障，之前其实主要从源码角度分析过redis 的 LRU 和 LFU，但这个是偏底层的实现，抠得比较细，那么具体的系统层面的配置是有哪些策略，来看下 redis labs 的介绍</p>
<table>
<thead>
<tr>
<th align="center"><strong>Policy</strong></th>
<th align="center"><strong>Description</strong></th>
</tr>
</thead>
<tbody><tr>
<td align="center">noeviction                    不逐出</td>
<td align="center">Returns an error if the memory limit has been reached when trying to insert more data，插入更多数据时，如果内存达到上限了，返回错误</td>
</tr>
<tr>
<td align="center">allkeys-lru                   所有的 key 使用 lru 逐出</td>
<td align="center">Evicts the least recently used keys out of all keys                                             在所有 key 中逐出最近最少使用的</td>
</tr>
<tr>
<td align="center">allkeys-lfu                   所有的 key 使用 lfu 逐出</td>
<td align="center">Evicts the least frequently used keys out of all keys                                   在所有 key 中逐出最近最不频繁使用的</td>
</tr>
<tr>
<td align="center">allkeys-random             所有的 key 中随机逐出</td>
<td align="center">Randomly evicts keys out of all keys                                                       在所有 key 中随机逐出</td>
</tr>
<tr>
<td align="center">volatile-lru</td>
<td align="center">Evicts the least recently used keys out of all keys with an “expire” field set    在设置了过期时间的 key 空间 expire 中使用 lru 策略逐出</td>
</tr>
<tr>
<td align="center">volatile-lfu</td>
<td align="center">Evicts the least frequently used keys out of all keys with an “expire” field set 在设置了过期时间的 key 空间 expire 中使用 lfu 策略逐出</td>
</tr>
<tr>
<td align="center">volatile-random</td>
<td align="center">Randomly evicts keys with an “expire” field set                                         在设置了过期时间的 key 空间 expire 中随机逐出</td>
</tr>
<tr>
<td align="center">volatile-ttl</td>
<td align="center">Evicts the shortest time-to-live keys out of all keys with an “expire” field set.在设置了过期时间的 key 空间 expire 中逐出更早过期的</td>
</tr>
</tbody></table>
<p>而在这其中默认使用的策略是 volatile-lru，对 lru 跟 lfu 想有更多的了解可以看下我之前的文章<a href="https://nicksxs.me/2020/04/18/redis%E7%B3%BB%E5%88%97%E4%BB%8B%E7%BB%8D%E5%85%AB/">redis系列介绍八-淘汰策略</a></p>
]]></content>
      <categories>
        <category>redis</category>
      </categories>
      <tags>
        <tag>redis</tag>
        <tag>淘汰策略</tag>
        <tag>应用</tag>
        <tag>Evict</tag>
      </tags>
  </entry>
  <entry>
    <title>redis过期策略复习</title>
    <url>/2021/07/25/redis%E8%BF%87%E6%9C%9F%E7%AD%96%E7%95%A5%E5%A4%8D%E4%B9%A0/</url>
    <content><![CDATA[<h1 id="redis过期策略复习"><a href="#redis过期策略复习" class="headerlink" title="redis过期策略复习"></a>redis过期策略复习</h1><p>之前其实写过redis的过期的一些原理，这次主要是记录下，一些使用上的概念，主要是redis使用的过期策略是懒过期和定时清除，懒过期的其实比较简单，即是在key被访问的时候会顺带着判断下这个key是否已过期了，如果已经过期了，就不返回了，但是这种策略有个漏洞是如果有些key之后一直不会被访问了，就等于沉在池底了，所以需要有一个定时的清理机制，去从设置了过期的key池子（expires）里随机地捞key，具体的策略我们看下官网的解释</p>
<ol>
<li>Test 20 random keys from the set of keys with an associated expire.</li>
<li>Delete all the keys found expired.</li>
<li>If more than 25% of keys were expired, start again from step 1.</li>
</ol>
<p>从池子里随机获取20个key，将其中过期的key删掉，如果这其中有超过25%的key已经过期了，那就再来一次，以此保持过期的key不超过25%（左右），并且这个定时策略可以在redis的配置文件</p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell"># Redis calls an internal function to perform many background tasks, like
# closing connections of clients in timeout, purging expired keys that are
# never requested, and so forth.
#
# Not all tasks are performed with the same frequency, but Redis checks for
# tasks to perform according to the specified &quot;hz&quot; value.
#
# By default &quot;hz&quot; is set to 10. Raising the value will use more CPU when
# Redis is idle, but at the same time will make Redis more responsive when
# there are many keys expiring at the same time, and timeouts may be
# handled with more precision.
#
# The range is between 1 and 500, however a value over 100 is usually not
# a good idea. Most users should use the default of 10 and raise this up to
# 100 only in environments where very low latency is required.
hz 10<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>可以配置这个hz的值，代表的含义是每秒的执行次数，默认是10，其实也用了hz的普遍含义。有兴趣可以看看之前写的一篇文章<a href="%5Bhttps://nicksxs.me/2020/04/12/redis%E7%B3%BB%E5%88%97%E4%BB%8B%E7%BB%8D%E4%B8%83/%5D(https://nicksxs.me/2020/04/12/redis%E7%B3%BB%E5%88%97%E4%BB%8B%E7%BB%8D%E4%B8%83/)">redis系列介绍七-过期策略</a></p>
]]></content>
      <categories>
        <category>redis</category>
      </categories>
      <tags>
        <tag>redis</tag>
        <tag>应用</tag>
        <tag>过期策略</tag>
      </tags>
  </entry>
  <entry>
    <title>rust学习笔记-所有权三之切片</title>
    <url>/2021/05/16/rust%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0-%E6%89%80%E6%9C%89%E6%9D%83%E4%B8%89%E4%B9%8B%E5%88%87%E7%89%87/</url>
    <content><![CDATA[<p>除了引用，Rust 还有另外一种不持有所有权的数据类型：切片(slice)。切片允许我们引用集合中某一段连续的元素序列，而不是整个集合。<br>例如代码</p>
<pre class="line-numbers language-rust" data-language="rust"><code class="language-rust"><span class="token keyword">fn</span> <span class="token function-definition function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">let</span> <span class="token keyword">mut</span> s <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token string">"hello world"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">let</span> word <span class="token operator">=</span> <span class="token function">first_word</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>s<span class="token punctuation">)</span><span class="token punctuation">;</span>

    s<span class="token punctuation">.</span><span class="token function">clear</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token comment">// 这时候虽然 word 还是 5，但是 s 已经被清除了，所以就没存在的意义</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这里其实我们就需要关注 s 的存在性，代码的逻辑合理性就需要额外去维护，此时我们就可以用切片</p>
<pre class="line-numbers language-rust" data-language="rust"><code class="language-rust"><span class="token keyword">let</span> s <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token string">"hello world"</span><span class="token punctuation">)</span>

<span class="token keyword">let</span> hello <span class="token operator">=</span> <span class="token operator">&amp;</span>s<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">..</span><span class="token number">5</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
<span class="token keyword">let</span> world <span class="token operator">=</span> <span class="token operator">&amp;</span>s<span class="token punctuation">[</span><span class="token number">6</span><span class="token punctuation">..</span><span class="token number">11</span><span class="token punctuation">]</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>其实跟 Python 的list 之类的语法有点类似，当然里面还有些语法糖，比如可以直接用省略后面的数字表示直接引用到结尾</p>
<pre class="line-numbers language-rust" data-language="rust"><code class="language-rust"><span class="token keyword">let</span> hello <span class="token operator">=</span> <span class="token operator">&amp;</span>s<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">..</span><span class="token punctuation">]</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>甚至再进一步</p>
<pre class="line-numbers language-rust" data-language="rust"><code class="language-rust"><span class="token keyword">let</span> hello <span class="token operator">=</span> <span class="token operator">&amp;</span>s<span class="token punctuation">[</span><span class="token punctuation">..</span><span class="token punctuation">]</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>使用了切片之后</p>
<pre class="line-numbers language-rust" data-language="rust"><code class="language-rust"><span class="token keyword">fn</span> <span class="token function-definition function">first_word</span><span class="token punctuation">(</span>s<span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token class-name">String</span><span class="token punctuation">)</span> <span class="token punctuation">-></span> <span class="token operator">&amp;</span><span class="token keyword">str</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">let</span> bytes <span class="token operator">=</span> s<span class="token punctuation">.</span><span class="token function">as_bytes</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">for</span> <span class="token punctuation">(</span>i<span class="token punctuation">,</span> <span class="token operator">&amp;</span>item<span class="token punctuation">)</span> <span class="token keyword">in</span> bytes<span class="token punctuation">.</span><span class="token function">iter</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">enumerate</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> item <span class="token operator">==</span> <span class="token char string">b' '</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> <span class="token operator">&amp;</span>s<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">..</span>i<span class="token punctuation">]</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token operator">&amp;</span>s<span class="token punctuation">[</span><span class="token punctuation">..</span><span class="token punctuation">]</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">fn</span> <span class="token function-definition function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">let</span> <span class="token keyword">mut</span> s <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token string">"hello world"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">let</span> word <span class="token operator">=</span> <span class="token function">first_word</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>s<span class="token punctuation">)</span><span class="token punctuation">;</span>

    s<span class="token punctuation">.</span><span class="token function">clear</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// error!</span>

    <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">"the first word is: &#123;&#125;"</span><span class="token punctuation">,</span> word<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>那再执行 main 函数的时候就会抛错，因为 word 还是个切片，需要保证 s 的有效性，并且其实我们可以将函数申明成</p>
<pre class="line-numbers language-rust" data-language="rust"><code class="language-rust"><span class="token keyword">fn</span> <span class="token function-definition function">first_word</span><span class="token punctuation">(</span>s<span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token keyword">str</span><span class="token punctuation">)</span> <span class="token punctuation">-></span> <span class="token operator">&amp;</span><span class="token keyword">str</span> <span class="token punctuation">&#123;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>这样就既能处理&amp;String 的情况，就是当成完整字符串的切片，也能处理普通的切片。<br>其他类型的切片</p>
<pre class="line-numbers language-rust" data-language="rust"><code class="language-rust"><span class="token keyword">let</span> a <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
<span class="token keyword">let</span> slice <span class="token operator">=</span> <span class="token operator">&amp;</span>a<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">..</span><span class="token number">3</span><span class="token punctuation">]</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>简单记录下，具体可以去看看这本书</p>
]]></content>
      <categories>
        <category>语言</category>
        <category>Rust</category>
      </categories>
      <tags>
        <tag>Rust</tag>
        <tag>所有权</tag>
        <tag>内存分布</tag>
        <tag>新语言</tag>
        <tag>可变引用</tag>
        <tag>不可变引用</tag>
        <tag>切片</tag>
      </tags>
  </entry>
  <entry>
    <title>rust学习笔记-所有权二</title>
    <url>/2021/04/18/rust%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0-%E6%89%80%E6%9C%89%E6%9D%83%E4%BA%8C/</url>
    <content><![CDATA[<p>这里需要说道函数和返回值了<br>可以看书上的这个例子<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/fnlsui.png"><br>对于这种情况，当进入函数内部时，会把传入的变量的所有权转移进函数内部，如果最后还是要返回该变量，但是如果此时还要返回别的计算结果，就可能需要笨拙地使用元组<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/6vBWwi.png"></p>
<h3 id="引用"><a href="#引用" class="headerlink" title="引用"></a>引用</h3><p>此时我们就可以用引用来解决这个问题</p>
<pre class="line-numbers language-rust" data-language="rust"><code class="language-rust"><span class="token keyword">fn</span> <span class="token function-definition function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">let</span> s1 <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token string">"hello"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">let</span> len <span class="token operator">=</span> <span class="token function">calculate_length</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>s1<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">"The length of '&#123;&#125;' is &#123;&#125;"</span><span class="token punctuation">,</span> s1<span class="token punctuation">,</span> len<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">fn</span> <span class="token function-definition function">calculate_length</span><span class="token punctuation">(</span>s<span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token class-name">String</span><span class="token punctuation">)</span> <span class="token punctuation">-></span> <span class="token keyword">usize</span> <span class="token punctuation">&#123;</span>
    s<span class="token punctuation">.</span><span class="token function">len</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这里的&amp;符号就是引用的语义，它们允许你在不获得所有权的前提下使用值<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/nniiIt.png"><br>由于引用不持有值的所有权，所以当引用离开当前作用域时，它指向的值也不会被丢弃</p>
<h3 id="可变引用"><a href="#可变引用" class="headerlink" title="可变引用"></a>可变引用</h3><p>而当我们尝试对引用的字符串进行修改时</p>
<pre class="line-numbers language-rust" data-language="rust"><code class="language-rust"><span class="token keyword">fn</span> <span class="token function-definition function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">let</span> s1 <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token string">"hello"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">change</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>s1<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">fn</span> <span class="token function-definition function">change</span><span class="token punctuation">(</span>s<span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token class-name">String</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    s<span class="token punctuation">.</span><span class="token function">push_str</span><span class="token punctuation">(</span><span class="token string">", world"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>就会有以下报错，<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/LVWURi.png"><br>其实也很容易发现，毕竟没有 mut 指出这是可变引用，同时需要将 s1 改成 mut 可变的</p>
<pre class="line-numbers language-rust" data-language="rust"><code class="language-rust"><span class="token keyword">fn</span> <span class="token function-definition function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">let</span> <span class="token keyword">mut</span> s1 <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token string">"hello"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">change</span><span class="token punctuation">(</span><span class="token operator">&amp;</span><span class="token keyword">mut</span> s1<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>


<span class="token keyword">fn</span> <span class="token function-definition function">change</span><span class="token punctuation">(</span>s<span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token keyword">mut</span> <span class="token class-name">String</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    s<span class="token punctuation">.</span><span class="token function">push_str</span><span class="token punctuation">(</span><span class="token string">", world"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>再看一个例子</p>
<pre class="line-numbers language-rust" data-language="rust"><code class="language-rust"><span class="token keyword">fn</span> <span class="token function-definition function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">let</span> <span class="token keyword">mut</span> s1 <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token string">"hello"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">let</span> r1 <span class="token operator">=</span> <span class="token operator">&amp;</span><span class="token keyword">mut</span> s1<span class="token punctuation">;</span>
    <span class="token keyword">let</span> r2 <span class="token operator">=</span> <span class="token operator">&amp;</span><span class="token keyword">mut</span> s1<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这个例子在书里是会报错的，因为同时存在一个以上的可变引用，但是在我运行的版本里前面这段没有报错，只有当我真的要去更改的时候</p>
<pre class="line-numbers language-rust" data-language="rust"><code class="language-rust"><span class="token keyword">fn</span> <span class="token function-definition function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">let</span> <span class="token keyword">mut</span> s1 <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token string">"hello"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">let</span> <span class="token keyword">mut</span> r1 <span class="token operator">=</span> <span class="token operator">&amp;</span><span class="token keyword">mut</span> s1<span class="token punctuation">;</span>
    <span class="token keyword">let</span> <span class="token keyword">mut</span> r2 <span class="token operator">=</span> <span class="token operator">&amp;</span><span class="token keyword">mut</span> s1<span class="token punctuation">;</span>
    <span class="token function">change</span><span class="token punctuation">(</span><span class="token operator">&amp;</span><span class="token keyword">mut</span> r1<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token function">change</span><span class="token punctuation">(</span><span class="token operator">&amp;</span><span class="token keyword">mut</span> r2<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>


<span class="token keyword">fn</span> <span class="token function-definition function">change</span><span class="token punctuation">(</span>s<span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token keyword">mut</span> <span class="token class-name">String</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    s<span class="token punctuation">.</span><span class="token function">push_str</span><span class="token punctuation">(</span><span class="token string">", world"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/k3jjNn.png"><br>这里可能就是具体版本在实现上的一个差异，我用的 rustc 是 1.44.0 版本<br>其实上面的主要是由 rust 想要避免这类多重可变更导致的异常问题，总结下就是三个点</p>
<ul>
<li>两个或两个以上的指针同时同时访问同一空间</li>
<li>其中至少有一个指针会想空间中写入数据</li>
<li>没有同步数据访问的机制<br>并且我们不能在拥有不可变引用的情况下创建可变引用<h3 id="悬垂引用"><a href="#悬垂引用" class="headerlink" title="悬垂引用"></a>悬垂引用</h3>还有一点需要注意的就是悬垂引用<pre class="line-numbers language-rust" data-language="rust"><code class="language-rust"><span class="token keyword">fn</span> <span class="token function-definition function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">let</span> reference_to_nothing <span class="token operator">=</span> <span class="token function">dangle</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>

<span class="token keyword">fn</span> <span class="token function-definition function">dangle</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">-></span> <span class="token operator">&amp;</span><span class="token class-name">String</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">let</span> s <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token string">"hello"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token operator">&amp;</span>s
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
这里可以看到其实在 dangle函数返回后，这里的 s 理论上就离开了作用域，但是由于返回了 s 的引用，在 main 函数中就会拿着这个引用，就会出现如下错误<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/JtrXSW.png"><h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3>最后总结下</li>
<li>在任何一个段给定的时间里，你要么只能拥有一个可变引用，要么只能拥有任意数量的不可变引用。</li>
<li>引用总是有效的。</li>
</ul>
]]></content>
      <categories>
        <category>语言</category>
        <category>Rust</category>
      </categories>
      <tags>
        <tag>Rust</tag>
        <tag>所有权</tag>
        <tag>内存分布</tag>
        <tag>新语言</tag>
        <tag>可变引用</tag>
        <tag>不可变引用</tag>
      </tags>
  </entry>
  <entry>
    <title>rust学习笔记-所有权一</title>
    <url>/2021/04/18/rust%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/</url>
    <content><![CDATA[<p>最近在看 《rust 权威指南》，还是难度比较大的，它里面的一些概念跟之前的用过的都有比较大的差别<br>比起有 gc 的虚拟机语言，跟像 C 和 C++这种主动释放内存的，rust 有他的独特点，主要是有三条</p>
<ul>
<li>Rust中的每一个值都有一个对应的变量作为它的所有者。</li>
<li>在同一时间内，值有且只有一个所有者。</li>
<li>当所有者离开自己的作用域时，它持有的值就会被释放掉。<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/U2pUVH.png"><br>这里有两个重点：</li>
<li>s 在进入作用域后才变得有效</li>
<li>它会保持自己的有效性直到自己离开作用域为止</li>
</ul>
<p>然后看个案例</p>
<pre class="line-numbers language-rust" data-language="rust"><code class="language-rust"><span class="token keyword">let</span> x <span class="token operator">=</span> <span class="token number">5</span><span class="token punctuation">;</span>
<span class="token keyword">let</span> y <span class="token operator">=</span> x<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>这个其实有两种，一般可以认为比较多实现的会使用 copy on write 之类的，先让两个都指向同一个快 5 的存储，在发生变更后开始正式拷贝，但是涉及到内存处理的便利性，对于这类简单类型，可以直接拷贝<br>但是对于非基础类型</p>
<pre class="line-numbers language-rust" data-language="rust"><code class="language-rust"><span class="token keyword">let</span> s1 <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token string">"hello"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">let</span> s2 <span class="token operator">=</span> s1<span class="token punctuation">;</span>

<span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">"&#123;&#125;, world!"</span><span class="token punctuation">,</span> s1<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>有可能认为有两种内存分布可能<br>先看下 string 的内存结构<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/mhfEjF.png"><br>第一种可能是<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/dDTQTu.png"><br>第二种是<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/ZNUCbc.png"><br>我们来尝试编译下<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/X6teOn.png"><br>发现有这个错误，其实在 rust 中<code>let y = x</code>这个行为的实质是移动，在赋值给 y 之后 x 就无效了<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/gfJcts.png"><br>这样子就不会造成脱离作用域时，对同一块内存区域的二次释放，如果需要复制，可以使用 clone 方法</p>
<pre class="line-numbers language-rust" data-language="rust"><code class="language-rust"><span class="token keyword">let</span> s1 <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token string">"hello"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">let</span> s2 <span class="token operator">=</span> s1<span class="token punctuation">.</span><span class="token function">clone</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">"s1 = &#123;&#125;, s2 = &#123;&#125;"</span><span class="token punctuation">,</span> s1<span class="token punctuation">,</span> s2<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>这里其实会有点疑惑，为什么前面的<code>x, y</code> 的行为跟 <code>s1, s2</code> 的不一样，其实主要是基本类型和 string 这类的不定大小的类型的内存分配方式不同，<code>x, y</code>这类整型可以直接确定大小，可以直接在栈上分配，而像 string 和其他的变体结构体，其大小都是不能在编译时确定，所以需要在堆上进行分配</p>
]]></content>
      <categories>
        <category>语言</category>
        <category>Rust</category>
      </categories>
      <tags>
        <tag>Rust</tag>
        <tag>所有权</tag>
        <tag>内存分布</tag>
        <tag>新语言</tag>
      </tags>
  </entry>
  <entry>
    <title>spark-little-tips</title>
    <url>/2017/03/28/spark-little-tips/</url>
    <content><![CDATA[<h2 id="spark-的一些粗浅使用经验"><a href="#spark-的一些粗浅使用经验" class="headerlink" title="spark 的一些粗浅使用经验"></a>spark 的一些粗浅使用经验</h2><p>工作中学习使用了一下Spark做数据分析,主要是用spark的python接口，首先是<code>pyspark.SparkContext(appName=xxx)</code>，这是初始化一个Spark应用实例或者说会话，不能重复，<br>返回的实例句柄就可以调用<code>textFile(path)</code>读取文本文件，这里的文本文件可以是HDFS上的文本文件，也可以普通文本文件，但是需要在Spark的所有集群上都存在，否则会<br>读取失败，<code>parallelize</code>则可以将python生成的集合数据读取后转换成rdd(A Resilient Distributed Dataset (RDD),一种spark下的基本抽象数据集),基于这个RDD就可以做<br>数据的流式计算，例如<code>map reduce</code>,在Spark中可以非常方便地实现  </p>
<h3 id="简单的mapreduce-word-count示例"><a href="#简单的mapreduce-word-count示例" class="headerlink" title="简单的mapreduce word count示例"></a>简单的mapreduce word count示例</h3><pre class="line-numbers language-Python" data-language="Python"><code class="language-Python">textFile &#x3D; sc.parallelize([(1,1), (2,1), (3,1), (4,1), (5,1),(1,1), (2,1), (3,1), (4,1), (5,1)])
data &#x3D; textFile.reduceByKey(lambda x, y: x + y).collect()
for _ in data:
    print(_)<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>


<h3 id="结果"><a href="#结果" class="headerlink" title="结果"></a>结果</h3><pre class="line-numbers language-none"><code class="language-none">(3, 2)
(1, 2)
(4, 2)
(2, 2)
(5, 2)<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
]]></content>
      <categories>
        <category>data analysis</category>
      </categories>
      <tags>
        <tag>spark</tag>
        <tag>python</tag>
      </tags>
  </entry>
  <entry>
    <title>summary-ranges-228</title>
    <url>/2016/10/12/summary-ranges-228/</url>
    <content><![CDATA[<h4 id="problem"><a href="#problem" class="headerlink" title="problem"></a>problem</h4><p>Given a sorted integer array without duplicates, return the summary of its ranges.</p>
<p>For example, given <code>[0,1,2,4,5,7]</code>, return <code>[&quot;0-&gt;2&quot;,&quot;4-&gt;5&quot;,&quot;7&quot;]</code>.</p>
<h4 id="题解"><a href="#题解" class="headerlink" title="题解"></a>题解</h4><p>每一个区间的起点<code>nums[i]</code>加上<code>j</code>是否等于<code>nums[i+j]</code><br><a href="http://www.cnblogs.com/grandyang/p/4603555.html">参考</a></p>
<h4 id="Code"><a href="#Code" class="headerlink" title="Code"></a>Code</h4><pre class="line-numbers language-C++" data-language="C++"><code class="language-C++">class Solution &#123;
public:
    vector&lt;string&gt; summaryRanges(vector&lt;int&gt;&amp; nums) &#123;
        int i &#x3D; 0, j &#x3D; 1, n;
        vector&lt;string&gt; res;
        n &#x3D; nums.size();
        while(i &lt; n)&#123;
            j &#x3D; 1;
            while(j &lt; n &amp;&amp; nums[i+j] - nums[i] &#x3D;&#x3D; j) j++;
            res.push_back(j &lt;&#x3D; 1 ? to_string(nums[i]) : to_string(nums[i]) + &quot;-&gt;&quot; + to_string(nums[i + j - 1]));
            i +&#x3D; j;
        &#125;
        return res;
    &#125;
&#125;;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>]]></content>
      <categories>
        <category>leetcode</category>
      </categories>
      <tags>
        <tag>leetcode</tag>
        <tag>c++</tag>
      </tags>
  </entry>
  <entry>
    <title>swoole-websocket-test</title>
    <url>/2016/07/13/swoole-websocket-test/</url>
    <content><![CDATA[<h3 id="玩一下swoole的websocket"><a href="#玩一下swoole的websocket" class="headerlink" title="玩一下swoole的websocket"></a>玩一下swoole的websocket</h3><p>WebSocket是HTML5开始提供的一种在单个<a href="https://zh.wikipedia.org/wiki/TCP">TCP</a>连接上进行<a href="https://zh.wikipedia.org/wiki/%E5%85%A8%E9%9B%99%E5%B7%A5">全双工</a>通讯的协议。WebSocket通信协议于2011年被<a href="https://zh.wikipedia.org/wiki/Internet_Engineering_Task_Force">IETF</a>定为标准RFC 6455，WebSocketAPI被W3C定为标准。<br>,在web私信，im等应用较多。背景和优缺点可以参看<a href="https://zh.wikipedia.org/wiki/WebSocket">wiki</a>。</p>
<h3 id="环境准备"><a href="#环境准备" class="headerlink" title="环境准备"></a>环境准备</h3><p>因为swoole官方还不支持windows，所以需要装下linux,之前都是用ubuntu，<br>这次就试一下centos7，还是满好看的，虽然虚拟机会默认最小安装，需要在安装<br>时自己选择带gnome的，当然最小安装也是可以的，只是最后需要改下防火墙。<br>然后是装下PHP，Nginx什么的，我是用<a href="https://oneinstack.com/">Oneinstack</a>，可以按需安装<br>给做这个的大大点个赞。</p>
<span id="more"></span>

<h2 id="swoole"><a href="#swoole" class="headerlink" title="swoole"></a>swoole</h2><p>1.install via pecl</p>
<pre class="line-numbers language-none"><code class="language-none">pecl install swoole<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>2.install from source</p>
<pre class="line-numbers language-none"><code class="language-none">sudo apt-get install php5-dev
git clone https:&#x2F;&#x2F;github.com&#x2F;swoole&#x2F;swoole-src.git
cd swoole-src
phpize
.&#x2F;configure
make &amp;&amp; make install<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>3.add extension</p>
<pre class="line-numbers language-none"><code class="language-none">extension &#x3D; swoole.so<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>4.test extension</p>
<pre class="line-numbers language-none"><code class="language-none">php -m | grep swoole<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>如果存在就代表安装成功啦</p>
<h2 id="Exec"><a href="#Exec" class="headerlink" title="Exec"></a>Exec</h2><p>实现代码看了这位仁兄的<a href="http://www.jianshu.com/p/fedbb9d2d999">代码</a></p>
<p>还是贴一下代码<br>服务端：</p>
<pre class="line-numbers language-php" data-language="php"><code class="language-php"><span class="token comment">//创建websocket服务器对象，监听0.0.0.0:9502端口</span>
<span class="token variable">$ws</span> <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">swoole_websocket_server</span><span class="token punctuation">(</span><span class="token string double-quoted-string">"0.0.0.0"</span><span class="token punctuation">,</span> <span class="token number">9502</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">//监听WebSocket连接打开事件</span>
<span class="token variable">$ws</span><span class="token operator">-></span><span class="token function">on</span><span class="token punctuation">(</span><span class="token string single-quoted-string">'open'</span><span class="token punctuation">,</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token variable">$ws</span><span class="token punctuation">,</span> <span class="token variable">$request</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token variable">$fd</span><span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token variable">$request</span><span class="token operator">-></span><span class="token property">fd</span><span class="token punctuation">;</span>
    <span class="token variable">$GLOBALS</span><span class="token punctuation">[</span><span class="token string single-quoted-string">'fd'</span><span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token variable">$fd</span><span class="token punctuation">;</span>
    <span class="token comment">//区别下当前用户</span>
    <span class="token variable">$ws</span><span class="token operator">-></span><span class="token function">push</span><span class="token punctuation">(</span><span class="token variable">$request</span><span class="token operator">-></span><span class="token property">fd</span><span class="token punctuation">,</span> <span class="token string double-quoted-string">"hello user<span class="token interpolation"><span class="token punctuation">&#123;</span><span class="token variable">$request</span><span class="token operator">-></span><span class="token property">fd</span><span class="token punctuation">&#125;</span></span>, welcome\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> 
<span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">//监听WebSocket消息事件</span>
<span class="token variable">$ws</span><span class="token operator">-></span><span class="token function">on</span><span class="token punctuation">(</span><span class="token string single-quoted-string">'message'</span><span class="token punctuation">,</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token variable">$ws</span><span class="token punctuation">,</span> <span class="token variable">$frame</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token variable">$msg</span> <span class="token operator">=</span>  <span class="token string single-quoted-string">'from'</span><span class="token operator">.</span><span class="token variable">$frame</span><span class="token operator">-></span><span class="token property">fd</span><span class="token operator">.</span><span class="token string double-quoted-string">":<span class="token interpolation"><span class="token punctuation">&#123;</span><span class="token variable">$frame</span><span class="token operator">-></span><span class="token property">data</span><span class="token punctuation">&#125;</span></span>\n"</span><span class="token punctuation">;</span>

    <span class="token keyword">foreach</span><span class="token punctuation">(</span><span class="token variable">$GLOBALS</span><span class="token punctuation">[</span><span class="token string single-quoted-string">'fd'</span><span class="token punctuation">]</span> <span class="token keyword">as</span> <span class="token variable">$aa</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
        <span class="token keyword">foreach</span><span class="token punctuation">(</span><span class="token variable">$aa</span> <span class="token keyword">as</span> <span class="token variable">$i</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
            <span class="token keyword">if</span><span class="token punctuation">(</span><span class="token variable">$i</span> <span class="token operator">!=</span> <span class="token variable">$frame</span><span class="token operator">-></span><span class="token property">fd</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token comment"># code...</span>
                <span class="token variable">$ws</span><span class="token operator">-></span><span class="token function">push</span><span class="token punctuation">(</span><span class="token variable">$i</span><span class="token punctuation">,</span><span class="token variable">$msg</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">//监听WebSocket连接关闭事件</span>
<span class="token variable">$ws</span><span class="token operator">-></span><span class="token function">on</span><span class="token punctuation">(</span><span class="token string single-quoted-string">'close'</span><span class="token punctuation">,</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token variable">$ws</span><span class="token punctuation">,</span> <span class="token variable">$fd</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">echo</span> <span class="token string double-quoted-string">"client-<span class="token interpolation"><span class="token punctuation">&#123;</span><span class="token variable">$fd</span><span class="token punctuation">&#125;</span></span> is closed\n"</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token variable">$ws</span><span class="token operator">-></span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>客户端：</p>
<pre class="line-numbers language-html" data-language="html"><code class="language-html"><span class="token doctype"><span class="token punctuation">&lt;!</span><span class="token doctype-tag">DOCTYPE</span> <span class="token name">html</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>html</span> <span class="token attr-name">lang</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>en<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>head</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>meta</span> <span class="token attr-name">charset</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>UTF-8<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>title</span><span class="token punctuation">></span></span>Title<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>title</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>head</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>body</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>msg<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>input</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>text<span class="token punctuation">"</span></span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>text<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>input</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>submit<span class="token punctuation">"</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>发送数据<span class="token punctuation">"</span></span> <span class="token attr-name">onclick</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>song()<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>body</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>script</span><span class="token punctuation">></span></span><span class="token script"><span class="token language-javascript">
    <span class="token keyword">var</span> msg <span class="token operator">=</span> document<span class="token punctuation">.</span><span class="token function">getElementById</span><span class="token punctuation">(</span><span class="token string">"msg"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">var</span> wsServer <span class="token operator">=</span> <span class="token string">'ws://0.0.0.0:9502'</span><span class="token punctuation">;</span>
    <span class="token comment">//调用websocket对象建立连接：</span>
    <span class="token comment">//参数：ws/wss(加密)：//ip:port （字符串）</span>
    <span class="token keyword">var</span> websocket <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">WebSocket</span><span class="token punctuation">(</span>wsServer<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//onopen监听连接打开</span>
    websocket<span class="token punctuation">.</span><span class="token function-variable function">onopen</span> <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">evt</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">//websocket.readyState 属性：</span>
        <span class="token comment">/*
        CONNECTING    0    The connection is not yet open.
        OPEN    1    The connection is open and ready to communicate.
        CLOSING    2    The connection is in the process of closing.
        CLOSED    3    The connection is closed or couldn't be opened.
        */</span>
        msg<span class="token punctuation">.</span>innerHTML <span class="token operator">=</span> websocket<span class="token punctuation">.</span>readyState<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span class="token punctuation">;</span>

    <span class="token keyword">function</span> <span class="token function">song</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
        <span class="token keyword">var</span> text <span class="token operator">=</span> document<span class="token punctuation">.</span><span class="token function">getElementById</span><span class="token punctuation">(</span><span class="token string">'text'</span><span class="token punctuation">)</span><span class="token punctuation">.</span>value<span class="token punctuation">;</span>
        document<span class="token punctuation">.</span><span class="token function">getElementById</span><span class="token punctuation">(</span><span class="token string">'text'</span><span class="token punctuation">)</span><span class="token punctuation">.</span>value <span class="token operator">=</span> <span class="token string">''</span><span class="token punctuation">;</span>
        <span class="token comment">//向服务器发送数据</span>
        websocket<span class="token punctuation">.</span><span class="token function">send</span><span class="token punctuation">(</span>text<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
      <span class="token comment">//监听连接关闭</span>
<span class="token comment">//    websocket.onclose = function (evt) &#123;</span>
<span class="token comment">//        console.log("Disconnected");</span>
<span class="token comment">//    &#125;;</span>

    <span class="token comment">//onmessage 监听服务器数据推送</span>
    websocket<span class="token punctuation">.</span><span class="token function-variable function">onmessage</span> <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">evt</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        msg<span class="token punctuation">.</span>innerHTML <span class="token operator">+=</span> evt<span class="token punctuation">.</span>data <span class="token operator">+</span><span class="token string">'&lt;br>'</span><span class="token punctuation">;</span>
<span class="token comment">//        console.log('Retrieved data from server: ' + evt.data);</span>
    <span class="token punctuation">&#125;</span><span class="token punctuation">;</span>
<span class="token comment">//监听连接错误信息</span>
<span class="token comment">//    websocket.onerror = function (evt, e) &#123;</span>
<span class="token comment">//        console.log('Error occured: ' + evt.data);</span>
<span class="token comment">//    &#125;;</span>

</span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>script</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>html</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>做了个循环，将当前用户的消息发送给同时在线的其他用户，比较简陋，如下图<br>user1:<br><img data-src="https://ooo.0o0.ooo/2016/07/13/578665c09066f.png" alt="NH}()5}1DTLTKZ%HUQ`4L(V.png](https://ooo.0o0.ooo/2016/07/13/578665c07d94c.png)
user2:
![QA_$_$MEL6ALWF48UZFRY1L.png](https://ooo.0o0.ooo/2016/07/13/578665c08a2d1.png)
user3:
![QK8EU5`9TQNYIG_4YFU@DJN.png"></p>
]]></content>
      <categories>
        <category>php</category>
      </categories>
      <tags>
        <tag>websocket</tag>
        <tag>swoole</tag>
      </tags>
  </entry>
  <entry>
    <title>wordpress 忘记密码的一种解决方法</title>
    <url>/2021/12/05/wordpress-%E5%BF%98%E8%AE%B0%E5%AF%86%E7%A0%81%E7%9A%84%E4%B8%80%E7%A7%8D%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95/</url>
    <content><![CDATA[<p>前阵子搭了个 WordPress，但是没怎么用，前两天发现忘了登录密码了，最近不知道是什么情况，chrome 的记住密码跟历史记录感觉有点问题，历史记录丢了不少东西，可能是时间太久了，但是理论上应该有 LRU 这种策略的，有些还比较常用，还有记住密码，因为个人域名都是用子域名分配给各个服务，有些记住了，有些又没记住密码，略蛋疼，所以就找了下这个方案。<br>当然这个方案不是最优的，有很多限制，首先就是要能够登陆 WordPress 的数据库，不然这个方法是没用的。<br>首先不管用什么方式（别违法）先登陆数据库，选择 WordPress 的数据库，可以看到里面有几个表，我们的目标就是 <code>wp_users</code> 表，用 <code>select</code> 查询看下可以看到有用户的数据，如果是像我这样搭着玩的没有创建其他用户的话应该就只有一个用户，那我们的表里的用户数据就只会有一条，当然多条的话可以通过用户名来找<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/9xEy8t.png"><br>然后可能我这个版本是这样，没有装额外的插件，密码只是经过了 MD5 的单向哈希，所以我们可以设定一个新密码，然后用 MD5 编码后直接更新进去</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">UPDATE</span> wp_users <span class="token keyword">SET</span> user_pass <span class="token operator">=</span> MD5<span class="token punctuation">(</span><span class="token string">'123456'</span><span class="token punctuation">)</span> <span class="token keyword">WHERE</span> ID <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>然后就能用自己的账户跟刚才更新的密码登录了。</p>
]]></content>
      <categories>
        <category>小技巧</category>
      </categories>
      <tags>
        <tag>WordPress</tag>
        <tag>小技巧</tag>
      </tags>
  </entry>
  <entry>
    <title>《垃圾回收算法手册读书》笔记之整理算法</title>
    <url>/2021/03/07/%E3%80%8A%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E7%AE%97%E6%B3%95%E6%89%8B%E5%86%8C%E8%AF%BB%E4%B9%A6%E3%80%8B%E7%AC%94%E8%AE%B0%E4%B9%8B%E6%95%B4%E7%90%86%E7%AE%97%E6%B3%95/</url>
    <content><![CDATA[<p>最近看了下这本垃圾回收算法手册，看到了第三章的标记-整理回收算法，做个简单的读书笔记</p>
<h3 id="双指针整理算法"><a href="#双指针整理算法" class="headerlink" title="双指针整理算法"></a>双指针整理算法</h3><p>对于一块待整理区域，通过两个指针，free 在区域的起始端，scan 指针在区域的末端，free 指针从前往后知道找到空闲区域，scan 从后往前一直找到存活对象，当 free 指针未与 scan 指针交叉时，会给 scan 位置的对象特定位置标记上 free 的地址，即将要转移的地址，不过这里有个限制，这种整理算法一般会用于对象大小统一的情况，否则 free 指针扫描时还需要匹配scan 指针扫描到的存活对象的大小。<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/yLQlgj.png"></p>
<h3 id="Lisp-2-整理算法"><a href="#Lisp-2-整理算法" class="headerlink" title="Lisp 2 整理算法"></a>Lisp 2 整理算法</h3><p>需要三次完整遍历堆区域<br>第一遍是遍历后将计算出所有对象的最终地址（转发地址）<br>第二遍是使用转发地址更新赋值器线程根以及被标记对象中的引用，该操作将确保它们指向对象的新位置<br>第三次遍历是relocate最终将存活对象移动到其新的目标位置</p>
<h3 id="引线整理算法"><a href="#引线整理算法" class="headerlink" title="引线整理算法"></a>引线整理算法</h3><p>这个真的长见识了，<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/6yeA7n.png"><br>可以看到，原来是 A，B，C 对象引用了 N，这里会在第一次遍历的时候把这种引用反过来，让 N 的对象头部保存下 A 的地址，表示这类引用，然后在遍历到 B 的时候在链起来，到最后就会把所有引用了 N 对象的所有对象通过引线链起来，在第二次遍历的时候就把更新A，B，C 对象引用的 N 地址，并且移动 N 对象</p>
<h3 id="单次遍历算法"><a href="#单次遍历算法" class="headerlink" title="单次遍历算法"></a>单次遍历算法</h3><p>这个一直提到过位图的实现方式，<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/Jqtuzu.png"><br>可以看到在第一步会先通过位图标记，标记的方式是位图的每一位对应的堆内存的一个字（这里可能指的是 byte 吧），然后将一个存活对象的内存区域的第一个字跟最后一个字标记，这里如果在通过普通的方式就还需要一个地方在存转发地址，但是因为具体的位置可以通过位图算出来，也就不需要额外记录了</p>
]]></content>
      <categories>
        <category>Java</category>
        <category>gc</category>
        <category>jvm</category>
      </categories>
      <tags>
        <tag>java</tag>
        <tag>gc</tag>
        <tag>标记整理</tag>
        <tag>垃圾回收</tag>
        <tag>jvm</tag>
      </tags>
  </entry>
  <entry>
    <title>介绍一下 RocketMQ</title>
    <url>/2020/06/21/%E4%BB%8B%E7%BB%8D%E4%B8%80%E4%B8%8B-RocketMQ/</url>
    <content><![CDATA[<p>说起消息队列一般Web后端做过一段时间开发的肯定会用过，在前司的时候用的是改良版的 NSQ，有点像 NOSQL 的简写版🙄，其实是个go 语言写的消息队列，<a href="https://github.com/nsqio/nsq">nsq</a> 看代码提交感觉最近更新的不是很勤，不过因为前司有专门的中间件团队，所以还是挺好用的，而且中间件团队的大牛也很厉害，一次都没碰到过丢消息之类的错误，然后现在公司用的是 RocketMQ，本着总还是要了解下的，并且消息队列也是服务端开发中一个很重要的中间件，因为不太有不需要用消息队列的后端团队了吧，原来对 nsq 也不是特别了解原理，就打算了解下 RocketMQ。</p>
<p>还是像我这样的小白专属，消息队列用来干啥，很多都是标准答案，用来削峰填谷的，这个完全对，只是我想结合场景说给像我这样的小白同学听，想想一个电商的下单功能，除了 AT 两家之外应该大部分都是接入的支付，那么下单支付完成后一般都是等支付回调，告诉你支付完成了（也有可能是失败了，或者超时了咱们主动去查），然后这个回调里我们自己的业务代码干点啥，首先比如是把订单状态改掉了，然后会有各类的操作，比如把优惠券核销了，把其他金钱相关的也核销了，把购物车里对应的商品给删了，还有更次要的，比如发个客服消息，让用户确认下地址的，给用户加积分的等等等等，想象下如果这些都是回调里一股脑儿做掉了，那可能你的代码健壮性跟相关服务的稳定性还有性能要达到一个非常高的水平才能让业务不出现异常，并且万一流量打起来了，这些重要的不重要的操作都会阻塞着，所以需要用一个消息队列，在接到回调后只处理极少的几个核心操作，完了就把这个消息丢进消息队列里，让各个业务方去消费这个消息，把客服消息发一下，给用户加个积分等等，这样子主要的业务流程需要处理的事情就少了，速度也加快了，这个例子呢不能严格算是削峰填谷的例子，不过也算是消息队列的比较典型的使用场景了，要说真实的削峰填谷的话其实可以这么理解，假如短时间内有 1w 个请求进来，系统能支持的 QPS 才 1000，那么正常情况下服务就挂了，或者被限流了，为了让服务正常，那么可以把这些请求先放进消息队列里，我服务端以拉的模式按我的处理能力来消费，这样就没啥问题了</p>
<p>扯了这么多来聊聊 RocketMQ 长啥样</p>
<p><img data-src="https://mystore-1255223546.cos.ap-chengdu.myqcloud.com/uPic/6073827-a998e005dd13967c.png" alt="6073827-a998e005dd13967c"></p>
<p>总共有四大部分：<strong>NameServer，Broker，Producer，Consumer。</strong></p>
<h4 id="NameServer"><a href="#NameServer" class="headerlink" title="NameServer"></a>NameServer</h4><p>NameServer是一个非常简单的Topic路由注册中心，其角色类似Dubbo中的zookeeper，支持Broker的动态注册与发现。主要包括两个功能：Broker管理，NameServer接受Broker集群的注册信息并且保存下来作为路由信息的基本数据。然后提供心跳检测机制，检查Broker是否还存活；路由信息管理，每个NameServer将保存关于Broker集群的整个路由信息和用于客户端查询的队列信息。然后Producer和Conumser通过NameServer就可以知道整个Broker集群的路由信息，从而进行消息的投递和消费。NameServer通常也是集群的方式部署，各实例间相互不进行信息通讯。Broker是向每一台NameServer注册自己的路由信息，所以每一个NameServer实例上面都保存一份完整的路由信息。当某个NameServer因某种原因下线了，Broker仍然可以向其它NameServer同步其路由信息，Producer,Consumer仍然可以动态感知Broker的路由的信息。</p>
<p>NameServer压力不会太大，正常情况主要负责维持心跳和提供Topic-Broker的关系数据。但有一点需要注意，Broker向Namesr发心跳时，会带上当前自己所负责的所有Topic信息，<strong>如果Topic个数太多，会导致一次心跳中，光Topic的数据就非常大，网络情况差的话，网络传输失败，心跳失败，导致Namesrv误认为Broker心跳失败。</strong></p>
<h4 id="Broker"><a href="#Broker" class="headerlink" title="Broker"></a>Broker</h4><p>Broker主要负责消息的存储、投递和查询以及服务高可用保证，为了实现这些功能，Broker包含了以下几个重要子模块。</p>
<ul>
<li>Remoting Module：整个Broker的实体，负责处理来自clients端的请求。</li>
<li>Client Manager：负责管理客户端(Producer/Consumer)和维护Consumer的Topic订阅信息</li>
<li>Store Service：提供方便简单的API接口处理消息存储到物理硬盘和查询功能。</li>
<li>HA Service：高可用服务，提供Master Broker 和 Slave Broker之间的数据同步功能。</li>
<li>Index Service：根据特定的Message key对投递到Broker的消息进行索引服务，以提供消息的快速查询。</li>
</ul>
<h6 id="Broker的特点"><a href="#Broker的特点" class="headerlink" title="Broker的特点"></a>Broker的特点</h6><p><strong>1.负载均衡：</strong>Broker上存Topic信息，<strong>Topic由多个队列组成，队列会平均分散在多个Broker上，</strong>而Producer的发送机制保证消息尽量平均分布到所有队列中，<strong>最终效果就是所有消息都平均落在每个Broker上。</strong></p>
<p><strong>2.动态伸缩能力（非顺序消息）</strong>：Broker的伸缩性体现在两个维度：Topic, Broker。</p>
<blockquote>
<p><strong>Topic维度：</strong>假如一个Topic的消息量特别大，但集群水位压力还是很低，就可以扩大该Topic的队列数，Topic的队列数跟发送、消费速度成正比。<br> <strong>Broker维度：</strong>如果集群水位很高了，需要扩容，直接加机器部署Broker就可以。Broker起来后想NameServer注册，Producer、Consumer通过NameServer发现新Broker，立即跟该Broker直连，收发消息。</p>
</blockquote>
<p><strong>3.高可用&amp;高可靠</strong></p>
<blockquote>
<p><strong>高可用：</strong>集群部署时一般都为主备，备机实时从主机同步消息，如果其中一个主机宕机，备机提供消费服务，但不提供写服务。<br> <strong>高可靠：</strong>所有发往broker的消息，有同步刷盘和异步刷盘机制；同步刷盘时，消息写入物理文件才会返回成功，异步刷盘时，只有机器宕机，才会产生消息丢失，broker挂掉可能会发生，但是机器宕机崩溃是很少发生的，除非突然断电</p>
</blockquote>
<h4 id="Producer"><a href="#Producer" class="headerlink" title="Producer"></a>Producer</h4><p>Producer与NameServer集群中的其中一个节点（随机选择）建立长连接，定期从NameServer获取Topic路由信息，并向提供Topic 服务的Master建立长连接，且定时向Master发送心跳。Producer完全无状态，可集群部署。<br> <strong>RocketMQ提供三种发送方式：</strong></p>
<blockquote>
<p><strong>同步：</strong>在广泛的场景中使用可靠的同步传输，如重要的通知信息、短信通知、短信营销系统等。<br> <strong>异步：</strong>异步发送通常用于响应时间敏感的业务场景，发送出去即刻返回，利用回调做后续处理。<br> <strong>一次性：</strong>一次性发送用于需要中等可靠性的情况，如日志收集，发送出去即完成，不用等待发送结果，回调等等。</p>
</blockquote>
<h6 id="生产者端的负载均衡"><a href="#生产者端的负载均衡" class="headerlink" title="生产者端的负载均衡"></a>生产者端的负载均衡</h6><p>生产者发送时，会自动轮询当前所有可发送的broker，一条消息发送成功，下次换另外一个broker发送，以达到消息平均落到所有的broker上。</p>
<h4 id="Consumer"><a href="#Consumer" class="headerlink" title="Consumer"></a>Consumer</h4><p>Consumer与NameServer集群中的其中一个节点（随机选择）建立长连接，定期从NameServer获取Topic路由信息，并向提供Topic服务的Master、Slave建立长连接，且定时向Master、Slave发送心跳。Consumer既可以从Master订阅消息，也可以从Slave订阅消息，消费者在向Master拉取消息时，Master服务器会根据拉取偏移量与最大偏移量的距离（判断是否读老消息，产生读I/O），以及从服务器是否可读等因素建议下一次是从Master还是Slave拉取。</p>
<h6 id="消费者端的负载均衡"><a href="#消费者端的负载均衡" class="headerlink" title="消费者端的负载均衡"></a>消费者端的负载均衡</h6><p>先讨论消费者的消费模式，<strong>消费者有两种模式消费：集群消费，广播消费。</strong></p>
<blockquote>
<p><strong>广播消费：每个消费者消费Topic下的所有队列。</strong><br> <strong>集群消费：一个topic可以由同一个ID下所有消费者分担消费。</strong><br> 具体例子：假如TopicA有6个队列，某个消费者ID起了2个消费者实例，那么每个消费者负责消费3个队列。如果再增加一个消费者ID相同消费者实例，即当前共有3个消费者同时消费6个队列，那每个消费者负责2个队列的消费。</p>
</blockquote>
<p>消费者端的负载均衡，就是集群消费模式下，同一个ID的所有消费者实例平均消费该Topic的所有队列。</p>
<p><strong>消费者从用户角度来看有两种类型：</strong></p>
<blockquote>
<p><strong>PullConsumer：主动从brokers处拉取消息。</strong>Consumer消费的一种类型，应用通常主动调用Consumer的拉消息方法从Broker服务器拉消息、主动权由应用控制。一旦获取了批量消息，应用就会启动消费过程。<br><strong>PushConsumer：Consumer消费的一种类型，该模式下Broker收到数据后会主动推送给消费端，该消费模式一般实时性较高。</strong></p>
</blockquote>
<h4 id="补充一些概念"><a href="#补充一些概念" class="headerlink" title="补充一些概念"></a>补充一些概念</h4><p><strong>Topic：主题，表示一类消息的集合，每个主题包含若干条消息，每条消息只能属于一个主题，是RocketMQ进行消息订阅的基本单位。</strong>Topic与生产者和消费者都是非常松散的关系，一个topic可以有0个或者1个或者多个生产者向其发送消息，换句话说，一个生产者可以同时向不同和topic发送消息。从消费者的解度来说，一个topic可能被0个或者一个或者多个消费组订阅，类似的，一个消费组可以订阅一个或者多个主题只要这个消费组的实例保持他们的订阅一致。</p>
<p><strong>Message：消息</strong>消息系统所传输信息的物理载体，生产和消费数据的最小单位，每条消息必须属于一个主题。RocketMQ中每个消息拥有唯一的Message ID，且可以携带具有业务标识的Key。系统提供了通过Message ID和Key查询消息的功能。。</p>
<p><strong>Message Queue：消息队列，</strong>一个主题被化分为一个或者多个子主题（sub-topics），“消息队列”.</p>
<p><strong>Tag：标签，为消息设置的标志，用于同一主题下区分不同类型的消息。来自同一业务单元的消息，可以根据不同业务目的在同一主题下设置不同标签。标签能够有效地保持代码的清晰度和连贯性，并优化RocketMQ提供的查询系统。消费者可以根据Tag实现对不同子主题的不同消费逻辑，实现更好的扩展性。</strong>使用tag，同一业务模块不同目的的messages就可以用相同topic不同tag来标识。Tags有益于保持你的代码干净而条理清晰，同时促进使用RocketMQ提供的查询系统的效率。Topic：主题，是生产者发送的消息和消费者拉取的消息的归类。Topic与生产者和消费者都是非常松散的关系，一个topic可以有0个或者1个或者多个生产者向其发送消息，换句话说，一个生产者可以同时向不同和topic发送消息。从消费者的解度来说，一个topic可能被0个或者一个或者多个消费组订阅，类似的，一个消费组可以订阅一个或者多个主题只要这个消费组的实例保持他们的订阅一致。</p>
<p><strong>Message Order：当使用DefaultMQPushConsumer时，你需要确定消费消息的方式：</strong></p>
<blockquote>
<p>Orderly：顺序地消费消息即表示消费的消息顺序同生产者发送的顺序一致。<br> Concurrently：并行消费。指定此方式消费，信息消费的最大并行数量仅受限于每个消费者客户端指定的线程池。</p>
</blockquote>
<p><strong>Consumer Group：消费组，</strong>同一类Consumer的集合，这类Consumer通常消费同一类消息且消费逻辑一致。消费者组使得在消息消费方面，实现负载均衡和容错的目标变得非常容易。要注意的是，消费者组的消费者实例必须订阅完全相同的Topic。RocketMQ 支持两种消息模式：集群消费（Clustering）和广播消费（Broadcasting）。<br><strong>Producer Group:生产者组，</strong>同一类Producer的集合，这类Producer发送同一类消息且发送逻辑一致。如果发送的是事务消息且原始生产者在发送之后崩溃，则Broker服务器会联系同一生产者组的其他生产者实例以提交或回溯消费。</p>
<p>上面的这些我主要参考了 RocketMQ 的 GitHub 介绍和一些优秀网文的介绍，侵权请联系我删除。</p>
]]></content>
      <categories>
        <category>MQ</category>
        <category>RocketMQ</category>
        <category>消息队列</category>
        <category>RocketMQ</category>
        <category>中间件</category>
        <category>RocketMQ</category>
      </categories>
      <tags>
        <tag>MQ</tag>
        <tag>消息队列</tag>
        <tag>RocketMQ</tag>
        <tag>削峰填谷</tag>
        <tag>中间件</tag>
      </tags>
  </entry>
  <entry>
    <title>介绍下最近比较实用的端口转发</title>
    <url>/2021/11/14/%E4%BB%8B%E7%BB%8D%E4%B8%8B%E6%9C%80%E8%BF%91%E6%AF%94%E8%BE%83%E5%AE%9E%E7%94%A8%E7%9A%84%E7%AB%AF%E5%8F%A3%E8%BD%AC%E5%8F%91/</url>
    <content><![CDATA[<h3 id="vscode-扩展转发"><a href="#vscode-扩展转发" class="headerlink" title="vscode 扩展转发"></a>vscode 扩展转发</h3><p>在日常使用云服务器的时候，如果要访问上面自建的 mysql，一般要不直接开对应的端口，然后需要对本地 ip 进行授权，但是这个方案会有比较多的限制，比如本地 ip 变了，比如是非固定出口 ip 的家用宽带，或者要在家里跟公司都要访问，如果对所有 ip 都授权的话会不安全，这个时候其实是用 ssh 端口转发是个比较安全方便的方式。<br>原来在这个之前其实对这块内容不太了解，后面是听朋友说的，vscode 的 <a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-ssh"><code>Remote - SSH</code></a> 扩展可以很方便的使用端口转发，在使用该扩展的时候，会在控制台位置里都出现一个”端口” tab<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/k51ca1.png"><br>如图中所示，我就是将一个服务器上的 mysql 的 3306 端口转发到本地的 3307 端口，至于为什么不用 3306 是因为本地我也有个 mysql 已经使用了 3306 端口，这个方法是使用的 vscode 的这个扩展，</p>
<h3 id="ssh-命令转发"><a href="#ssh-命令转发" class="headerlink" title="ssh 命令转发"></a>ssh 命令转发</h3><p>还有个方式是直接使用 ssh 命令<br>命令可以如此</p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell">ssh -CfNg -L 3307:127.0.0.1:3306 user1@199.199.199.199<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>简单介绍下这个命令<br><code>-C</code> 表示的是压缩数据包<br><code>-f</code> 表示后台执行命令<br><code>-N</code> 是表示不执行具体命令只用于端口转发<br><code>-g</code> 表示允许远程主机连接本地转发端口<br><code>-L</code> 则是具体端口转发的映射配置<br>上面的命令就是将远程主机的 127.0.0.1:3306 对应转发到本地 3307<br>而后面的用户则就是登录主机的用户名<code>user1</code>和ip地址<code>199.199.199.199</code>，当然这个配置也不是唯一的</p>
<h3 id="ssh-config-配置转发"><a href="#ssh-config-配置转发" class="headerlink" title="ssh config 配置转发"></a>ssh config 配置转发</h3><p>还可以在ssh 的 config 配置中加对应的配置</p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell">Host host1
  HostName 199.199.199.199
  User user1
  IdentityFile  &#x2F;Users&#x2F;user1&#x2F;.ssh&#x2F;id_rsa
  ServerAliveInterval 60
  LocalForward 3310 127.0.0.1:3306<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>然后通过 ssh host1 连接服务器的时候就能顺带做端口转发</p>
]]></content>
      <categories>
        <category>ssh</category>
        <category>技巧</category>
      </categories>
      <tags>
        <tag>ssh</tag>
        <tag>端口转发</tag>
      </tags>
  </entry>
  <entry>
    <title>从丁仲礼被美国制裁聊点啥</title>
    <url>/2020/12/20/%E4%BB%8E%E4%B8%81%E4%BB%B2%E7%A4%BC%E8%A2%AB%E7%BE%8E%E5%9B%BD%E5%88%B6%E8%A3%81%E8%81%8A%E7%82%B9%E5%95%A5/</url>
    <content><![CDATA[<p>几年前看了柴静的《穹顶之下》觉得这个记者调查得很深入，挺有水平，然后再看到了她跟丁仲礼的采访，其实没看完整，也没试着去理解，就觉得环境问题挺严重的，为啥柴静这个对面的这位好像对这个很不屑的样子，最近因为丁仲礼上了美国制裁名单，B 站又有人把这个视频发了出来，就完整看了下，就觉得自己挺惭愧的，就抱着对柴静的好感而没来由的否定了丁老的看法和说法，所以人也需要不断地学习，改正之前错误的观点，当然不是说我现在说的就是百分百正确，只是个人的一些浅显的见解</p>
<p>先聊聊这个事情，整体看下来我的一些理解，IPCC给中国的方案其实是个很大的陷阱，它里面有几个隐藏的点是容易被我们外行忽略的，第一点是基数，首先发达国家目前（指2010年采访或者IPCC方案时间）的人均碳排放量已经是远高于发展中国家的了，这也就导致了所谓的发达国家承诺减排80%是个非常有诚意的承诺其实就是忽悠；第二点是碳排放是个累计过程，从1900年开始到2050年，或者说到2010年，发达国家已经排的量是远超过发展中国家的，这是非常不公平的；第三点其实是通过前两点推导出来的，也就是即使发达国家这么有诚意地说减排80%，扒开这层虚伪的外衣，其实是给他们11亿人分走了48%的碳排放量，留给发展中国家55亿人口的只剩下了52%；第四点，人是否因为国家的发达与否而应受到不平等待遇，如果按国家维度，丁老说的，摩纳哥要跟中国分同样的排放量么，中国人还算不算人；第五点，这点算是我自己想的，也可能是柴静屁股决定脑袋想不到的点，她作为一个物质生活条件已经足够好了，那么对于那些生活在物质条件平均线以下的，他们是否能像城里人那样有空调地暖，洗澡有热水器浴霸，上下班能开车，这些其实都直接或者间接地导致了碳排放；他们有没有改善物质生活条件地权利呢，并且再说回来，其实丁老也给了我们觉得合理地方案，我们保证不管发达国家不管减排多少，我们都不会超过他们的80%，我觉得这是真正的诚意，而不是接着减排80%的噱头来忽悠人，也是像丁老这样的专家才能看破这个陷阱，碳排放权其实就是发展权，就是人权，中国人就不是人了么，或者说站在贫困线以下的人民是否有改善物质条件的权利，而不是说像柴静这样，只是管她自己，可能觉得小孩因为空气污染导致身体不好，所以做了穹顶之下这个纪录片，想去改善这个事情，空气污染不是说对的，只是每个国家都有这个过程，如果不发展，哪里有资源去让人活得好，活得好了是前提，然后再去各方面都改善。</p>
<p>对于这个问题其实更想说的是人的认知偏差，之前总觉得美帝是更自由民主，公平啥的，或者说觉得美帝啥都好，有种无脑愤青的感觉，外国的月亮比较圆，但是经历了像川普当选美国总统以来的各种魔幻操作，还有对于疫情的种种不可思议的美国民众的反应，其实更让人明白第一是外国的月亮没比较圆，第二是事情总是没那么简单粗暴非黑即白，美国不像原先设想地那么领先优秀，但是的确有很多方面是全球领先的，天朝也有体制所带来的优势，不可妄自菲薄，也不能忙不自大，还是要多学习知识，提升认知水平。</p>
]]></content>
      <categories>
        <category>生活</category>
        <category>吐槽</category>
        <category>疫情</category>
        <category>美国</category>
      </categories>
      <tags>
        <tag>生活</tag>
        <tag>吐槽</tag>
        <tag>疫情</tag>
        <tag>美国</tag>
      </tags>
  </entry>
  <entry>
    <title>从清华美院学姐聊聊我们身边的恶人</title>
    <url>/2020/11/29/%E4%BB%8E%E6%B8%85%E5%8D%8E%E7%BE%8E%E9%99%A2%E5%AD%A6%E5%A7%90%E8%81%8A%E8%81%8A%E6%88%91%E4%BB%AC%E8%BA%AB%E8%BE%B9%E7%9A%84%E6%81%B6%E4%BA%BA/</url>
    <content><![CDATA[<p>前几天清华美院学姐的热点火了，然后仔细看了下，其实是个学姐诬陷以为其貌不扬的男同学摸她屁股<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/ZovTIK.jpg"><br>然后还在朋友圈发文想让他社死，我也是挺晚才知道这个词什么意思，然后后面我看到了这个图片，挺有意思的<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/%E6%91%B8%E5%B1%81%E8%82%A1.png"><br>本来其实也没什么想聊这个的，是在 B 站看了个吐槽这个的，然后刚好晚上乘公交的时候又碰到了有点类似的问题<br>故事描述下，我们从始发站做了公交，这辆公交司机上次碰到过一回，就是会比较关注乘客的佩戴情况，主要考虑到目前国内疫情，然后这次在差不多人都坐满的情况下，可能在提示了三次让车内乘客戴好口罩，但是他指的那个中年女性还是没有反应，司机就转头比较大声指着这个乘客（中年女性）让戴好口罩，然后这个乘客（中年女性）就大声的说“我口罩是滑下来了，你指着我干嘛，你态度这么差，要吃了我一样，我要投诉你”等等，然后可能跟她一块的一个中年女性也是这么帮腔指责司机，比较基本的理解，车子里这么多乘客，假如是处于这位乘客口罩滑下来了而不自知的情况下，司机在提示了三次以后回头指着她说，我想的是没什么问题的，但是这位却反而指责这位司机指着她，并且说是态度差，要吃了她，完全是不可理喻的，并且一直喋喋不休说她口罩滑掉了有什么错，要投诉这个司机，让他可以提前退休了，在其他乘客的劝说下司机准备继续开车时，又口吐芬芳“你个傻<em>，你来打我呀”，真的是让我再次体会到了所谓的恶人先告状的又一完美呈现，后面还有个乘客还是表示要打死司机这个傻</em>，让我有点不明所以，俗话说有人是得理不饶人，前提是得理，这种理亏不饶人真的是挺让人长见识的，试想下，司机在提示三次后，这位乘客还是没有把口罩戴好，如何在不指着这位乘客的情况下能准确的提示到她呢，并且觉得语气态度不好，司机要载着一车的人，因为你这一个乘客不戴好口罩而不能正常出发，有些着急应该很正常吧，可能是平时自己在家里耀武扬威的使唤别人习惯了吧，别人不敢这么大声跟她说话，其实想想这位中年女性应该年纪不会很大，还比较时髦的吧，像一些常见的中年杭州本地人可能是不会说傻*这个词的吧。<br>杭州的公交可能是在二月份疫情还比较严重的时候是要求上车出示健康码，后面比较缓和以后只要求佩戴好口罩，但是在我们小绍兴，目前还是一律要求检验健康码和佩戴口罩，对于疫情中，并且目前阶段国内也时有报出小范围的疫情的情况下，司机尽职要求佩戴好口罩其实也是为了乘客着想，另一种情况如果司机不严格要求，万一车上有个感染者，这位中年女性被传染了，如果能找到这个司机的话，是不是想“打死”这个司机，竟然让感染者上了车，反正她自己是不可能有错的，上来就是对方态度差，要投诉，自己不戴好口罩啥都没错，我就想知道如果因为自己没戴好口罩被感染了，是不是也是司机的错，毕竟没有像仆人那样点头哈腰求着她戴好口罩。<br>再说回来，整个车就她一个人没戴好口罩，并且还有个细节，其实这个乘客是上了车之后就没戴好了，本来上车的时候是戴好的，这种比较有可能是觉得上车的时候司机那看一眼就好了，如果好好戴着口罩，一点事情都没有，唉，纯粹是太气愤了，调理逻辑什么的就忽略吧</p>
]]></content>
      <categories>
        <category>生活</category>
        <category>吐槽</category>
        <category>疫情</category>
        <category>口罩</category>
      </categories>
      <tags>
        <tag>生活</tag>
        <tag>吐槽</tag>
        <tag>疫情</tag>
        <tag>公交车</tag>
        <tag>口罩</tag>
        <tag>杀人诛心</tag>
      </tags>
  </entry>
  <entry>
    <title>关于公共交通再吐个槽</title>
    <url>/2021/03/21/%E5%85%B3%E4%BA%8E%E5%85%AC%E5%85%B1%E4%BA%A4%E9%80%9A%E5%86%8D%E5%90%90%E4%B8%AA%E6%A7%BD/</url>
    <content><![CDATA[<p>事情源于周末来回家发生的两件事情，先是回去的时候从高铁下车要坐公交，现在算是有个比较好的临时候车点了，但是可能由于疫情好转，晚上都不用检查健康码就可以进候车点，但是上公交的时候还是需要看健康码，一般情况下从高铁下来的，各个地方的人都有，而且也不太清楚这边上公交车需要查验健康码，我的一个看法是候车的时候就应该放个横幅告示，或者再配合喇叭循环播放，请提前准备好健康码，上车前需要查验，因为像这周的情况，我乘坐的那辆车是间隔时间比较长，而且终点是工业开发区，可能是比较多外来务工人员的目的地，正好这部分人可能对于操作手机检验健康码这个事情不太熟悉，所以结果就是头上几个不知道怎么搞出来健康码，然后让几乎有满满一整车的人在后面堵着，司机又非常厌烦那些没有提前出示健康码的，有位乘客搞得久了点，还被误以为没刷卡买票，差点吵起来，其实公共交通或者高铁站负责的在公交指引路线上多写一句上车前需要查验健康码，可能就能改善比较多，还有就是那个积水的路，这个吐槽起来就一大坨了，整个绍兴像 dayuejin 一样到处都是破路。<br>第二个就是来杭州的时候，经过人行横道，远处车道的公交车停下来等我们了，为了少添麻烦总想快点穿过去，但是这时靠近我们的车道（晚上光线较暗，可见度不佳）有一辆从远处来的奥迪 A4 还是 A5 这种的车反而想加速冲过去，如果少看一下可能我已经残了，交规考的靠近人行道要减速好像基本都是个摆设了，杭州也只有公交车因为一些考核指标原因会主动礼让，人其实需要有同理心，虽然可能有些人是开车多于骑车走路的，但是总也不可能永远不穿人行道吧，甚至这些人可能还会在人行道红灯的时候走过去。这个事情不是吐槽公共交通的，只是也有些许关系，想起来还有一件事也是刚才来杭州的时候看到的，等公交的时候看到有辆路虎要加塞，而目标车道刚好是辆大货车，大货车看到按了喇叭，路虎犹豫了下还是挤进去了，可能是对路虎的扛撞性能非常自信吧，反正我是挺后怕的，这种级别的车，被撞了的话估计还是鸡蛋撞石头，吨位惯性在那，这里再延伸下，挺多开豪车的人好像都觉得这路上路权更大一些，谁谁都得让着他，可能实际吃亏的不多，所以越加巩固了这种思维，当真的碰到不管的可能就会明白了，路权这个事情在天朝也基本没啥人重视，也没想说个结论，就到这吧</p>
]]></content>
      <categories>
        <category>生活</category>
        <category>公交</category>
      </categories>
      <tags>
        <tag>生活</tag>
        <tag>开车</tag>
        <tag>加塞</tag>
        <tag>糟心事</tag>
        <tag>规则</tag>
        <tag>公交</tag>
        <tag>路政规划</tag>
        <tag>基础设施</tag>
        <tag>杭州</tag>
        <tag>健康码</tag>
      </tags>
  </entry>
  <entry>
    <title>关于读书打卡与分享</title>
    <url>/2021/02/07/%E5%85%B3%E4%BA%8E%E8%AF%BB%E4%B9%A6%E6%89%93%E5%8D%A1%E4%B8%8E%E5%88%86%E4%BA%AB/</url>
    <content><![CDATA[<p>最近群里大佬发起了一个读书打卡活动，需要每天读一会书，在群里打卡分享感悟，争取一个月能读完一本书，说实话一天十分钟的读书时间倒是问题不大，不过每天都要打卡，而且一个月要读完一本书，其实难度还是有点大的，不过也想试试看。<br>之前某某老大给自己立了个 flag，说要读一百本书，这对我来说挺难实现的，一则我也不喜欢书只读一小半，二则感觉对于喜欢看的内容范围还是比较有限制，可能也算是比较矫情，不爱追热门的各类东西，因为往往会有一些跟大众不一致的观点看法，显得格格不入。所以还是这个打卡活动可能会比较适合我，书是人类进步的阶梯。<br>到现在是打卡了三天了，读的主要是白岩松的《幸福了吗》，对于白岩松，我们这一代人是比较熟悉，并且整体印象比较不错的一个央视主持人，从《焦点访谈》开始，到疫情期间的各类一线节目，可能对我来说是个三观比较正，敢于说一些真话的主持人，这中间其实是有个空档期，没怎么看电视，也不太关注了，只是在疫情期间的节目，还是一如既往地给人一种可靠的感觉，正好有一次偶然微信读书推荐了白岩松的这本书，就看了一部分，正好这次继续往下看，因为相对来讲不会很晦涩，并且从这位知名央视主持人的角度分享他的过往和想法看法，还是比较有意思的。<br>从对汶川地震，08 年奥运等往事的回忆和一些细节的呈现，也让我了解比较多当时所不知道的，特别是汶川地震，那时的我还在读高中，真的是看着电视，作为“猛男”都忍不住泪目了，共和国之殇，多难兴邦，但是这对于当事人来说，都是一场醒不过来的噩梦。<br>然后是对于足球的热爱，其实光这个就能掰扯很多，因为我不爱足球，只爱篮球，其中原因有的没的也挺多可以说的，但是看了他的书，才能比较深入的了解一个足球迷，对足球，对中国足球，对世界杯，对阿根廷的感情。<br>接下去还是想能继续坚持下去，加油！</p>
]]></content>
      <categories>
        <category>生活</category>
        <category>读后感</category>
        <category>白岩松</category>
        <category>幸福了吗</category>
      </categories>
      <tags>
        <tag>读后感</tag>
        <tag>读书</tag>
        <tag>打卡</tag>
        <tag>幸福了吗</tag>
        <tag>足球</tag>
      </tags>
  </entry>
  <entry>
    <title>周末我在老丈人家打了天小工</title>
    <url>/2020/08/16/%E5%91%A8%E6%9C%AB%E6%88%91%E5%9C%A8%E8%80%81%E4%B8%88%E4%BA%BA%E5%AE%B6%E6%89%93%E4%BA%86%E5%A4%A9%E5%B0%8F%E5%B7%A5/</url>
    <content><![CDATA[<p>这周回家提前约好了要去老丈人家帮下忙，因为在翻修下老房子，活不是特别整的那种，所以大部分都是自己干，或者找个大工临时干几天（我们这那种比较专业的泥工匠叫做大工），像我这样去帮忙的，就是干点小工（把给大工帮忙的，干些偏体力活的叫做小工）的活。从大学毕业以后真的蛮少帮家里干活了，以前上学的时候放假还是帮家里淘个米，简单的扫地拖地啥的，当然刚高考完的时候，还去我爸厂里帮忙干了几天的活，实在是比较累，不过现在想着是觉得自己那时候比较牛，而不是特别排斥这个活，相对于现在的工作来说，导致了一系列的职业病，颈椎腰背都很僵硬，眼镜也不好，还有反流，像我爸那种活反而是脑力加体力的比较好的结合。<br>这一天的活前半部分主要是在清理厨房，瓷砖上的油污和墙上天花板上即将脱落的石灰或者白色涂料层，这种活特别是瓷砖上的油污，之前在自己家里也干活，还是比较熟悉的，不过前面主要是LD 在干，我主要是先搞墙上和天花板上的，干活还是很需要技巧的，如果直接去铲，那基本我会变成一个灰人，而且吸一鼻子灰，老丈人比较专业，先接上软管用水冲，一冲效果特别好，有些石灰涂料层直接就冲掉了，冲完之后先用带加长杆的刀片铲铲了一圈墙面，说实话因为老房子之前租出去了，所以墙面什么的被糟蹋的比较难看，一层一层的，不过这还算还好，后面主要是天花板上的，这可难倒我了，从小我爸妈是比较把我当小孩管着，爬上爬下的基本都是我爸搞定，但是到了老丈人家也只得硬着头皮上了，爬到跳（一种建筑工地用的架子）上，还有点晃，小心脏扑通扑通跳，而且带加长杆的铲子还是比较重的，铲一会手也有点累，不过坚持着铲完了，上面还是比较平整的，不过下来的时候又把我难住了🤦‍♂️，往下爬的时候有根杆子要跨过去，由于裤子比较紧，强行一把跨过去怕抽筋，所以以一个非常尴尬的姿势停留休息了一会，再跨了过去，幸好事后问 LD，他们都没看到，哈哈哈，然后就是帮忙一起搞瓷砖上的油污，这个太有经验了，不过老丈人更有意思，一会试试啤酒，一会用用沙子，后面在午饭前基本就弄的比较干净了，就坐着等吃饭了，下午午休了会，就继续干活了。<br>下午是我这次体验的重点了，因为要清理以前贴的墙纸，真的是个很麻烦的活，只能说贴墙纸的师傅活干得太好了，基本不可能整个撕下来，想用铲子一点点铲下来也不行，太轻了就只铲掉表面一层，太重了就把墙纸跟墙面的石灰啥的整个铲下来了，而且手又累又酸，后来想着是不是继续用水冲一下，对着一小面墙试验了下，效果还不错，但是又发现了个问题，那一面墙又有一块是后面糊上去的，铲掉外层的石灰后不平，然后就是最最重头的，也是让我后遗症持续到第二天的，要把那一块糊上去的水泥敲下来，毛估下大概是敲了80%左右，剩下的我的手已经不会用力了，因为那一块应该是要糊上去的始作俑者，就一块里面凹进去的，我拿着榔头敲到我手已经没法使劲了，而且大下午，感觉没五分钟，我的汗已经糊满脸，眼睛也睁不开，不然就流到眼睛里了，此处获得成就一：用榔头敲墙壁，也是个技术加体力的活，而且需要非常好的技巧，否则手马上就废了，敲下去的反作用力，没一会就不行了，然后是看着老丈人兄弟帮忙拆一个柜子，在我看来是个几天都搞不定的活，他轻轻松松在我敲墙的那会就搞定了，以前总觉得我干的活非常有技术含量，可是这个事情真的也是很有技巧啊，它是个把一间房间分隔开的柜子，从底到顶上，还带着门，我还在旁边帮忙撬一下脚踢，一根木条撬半天，唉，成就二：专业的人就是不一样。<br>最后就是成就三了：我之前沾沾自喜的跑了多少步，做了什么锻炼，其实都是渣渣，像这样干一天活，没经历过的，基本大半天就废了，反过来说，如果能经常去这么干一天活，跑步啥的都是渣渣，消耗的能量远远超过跑个十公里啥的。</p>
]]></content>
      <categories>
        <category>生活</category>
        <category>运动</category>
        <category>跑步</category>
        <category>干活</category>
      </categories>
      <tags>
        <tag>生活</tag>
        <tag>运动</tag>
        <tag>减肥</tag>
        <tag>跑步</tag>
        <tag>干活</tag>
      </tags>
  </entry>
  <entry>
    <title>在老丈人家的小工记三</title>
    <url>/2020/09/13/%E5%9C%A8%E8%80%81%E4%B8%88%E4%BA%BA%E5%AE%B6%E7%9A%84%E5%B0%8F%E5%B7%A5%E8%AE%B0%E4%B8%89/</url>
    <content><![CDATA[<h2 id="小工记三"><a href="#小工记三" class="headerlink" title="小工记三"></a>小工记三</h2><p>前面这两周周末也都去老丈人家帮忙了，上上周周六先是去了那个在装修的旧房子那，把三楼收拾了下，因为要搬进来住，来不及等二楼装修好，就要把三楼里的东西都整理干净，这个活感觉是比较 easy，原来是就准备把三楼当放东西仓储的地方了，我们乡下大部分三层楼都是这么用的，这次也是没办法，之前搬进来的木头什么的都搬出去，主要是这上面灰尘太多，后面清理鼻孔的时候都是黑色的了，把东西都搬出去以后主要是地还是很脏，就扫了地拖了地，因为是水泥地，灰尘又太多了，拖起来都是会灰尘扬起来，整个脱完了的确干净很多，然而这会就出了个大乌龙，我们清理的是三楼的西边一间，结果老丈人上来说要住东边那间的🤦‍♂️，不过其实西边的也得清理，因为还是要放被子什么的，不算是白费功夫，接着清理东边那间，之前这个房子做过群租房，里面有个高低铺的床，当时觉得可以用在放被子什么的就没扔，只是拆掉了放旁边，我们就把它擦干净了又装好，发现螺丝🔩少了几个，亘古不变的真理，拆了以后装要不就多几个要不就少几个，不是很牢靠，不过用来放放被子省得放地上总还是可以的，对了前面还做了个事情就是铺地毯，其实也不是地毯，就是类似于墙布雨篷布那种，别人不用了送给我们的，三楼水泥地也不会铺瓷砖地板了就放一下，干净好看点，不过大小不合适要裁一下，那把剪刀是真的太难用了，我手都要抽筋了，它就是刀口只有一小个点是能剪下来的，其他都是钝的，后来还是用刀片直接裁，铺好以后，真的感觉也不太一样了，焕然一新的感觉<br>差不多中午了就去吃饭了，之前两次是去了一家小饭店，还是还比较干净，但是店里菜不好吃，还死贵，这次去了一家小快餐店，口味好，便宜，味道是真的不错，带鱼跟黄鱼都好吃，一点都不腥，我对这类比较腥的鱼真的是很挑剔的，基本上除了家里做的很少吃外面的，那天抱着试试的态度吃了下，真的还不错，后来丈母娘说好像这家老板是给别人结婚喜事酒席当厨师的，怪不得做的好吃，其实本来是有一点小抗拒，怕不干净什么的，后来发现菜很好吃，而且可能是老丈人跟干活的师傅去吃的比较多，老板很客气，我们吃完饭，还给我们买了葡萄吃，不过这家店有一个槽点，就是饭比较不好吃，有时候会夹生，不过后面聊起来其实是这种小菜馆饭点的通病，烧的太早太多容易多出来浪费，烧的迟了不够吃，而且大的电饭锅比较不容易烧好。<br>下午前面还是在处理三楼的，窗户上各种钉子，实在是太多了，我后面在走廊上排了一排🤦‍♂️，有些是直接断了，有些是就撬了出来，感觉我在杭州租房也没有这样子各种钉钉子，挂下衣服什么的也不用这么多吧，比较不能理解，搞得到处都是钉子。那天我爸也去帮忙了，主要是在卫生间里做白缝，其实也是个技术活，印象中好像我小时候自己家里也做过这个事情，但是比较模糊了，后面我们三楼搞完了就去帮我爸了，前面是我老婆二爹在那先刷上白缝，这里叫白缝，有些考究的也叫美缝，就是瓷砖铺完之后的缝，如果不去弄的话，里面水泥的颜色就露出来了，而且容易渗水，所以就要用白水泥加胶水搅拌之后糊在缝上，但是也不是直接糊，先要把缝抠一抠，因为铺瓷砖的还不会仔细到每个缝里的水泥都是一样满，而且也需要一些空间糊上去，不然就太表面的一层很容易被水直接冲掉了，然后这次其实也不是用的白水泥，而是直接现成买来就已经配好的用来填缝的，兑水搅拌均匀就好了，后面就主要是我跟我爸在搞，那个时候真的觉得我实在是太胖了，蹲下去真的没一会就受不了了，膝盖什么的太难受了，后面我跪着刷，然后膝盖又疼，也是比较不容易，不过我爸动作很快，我中间跪累了休息一会，我爸就能搞一大片，后面其实我也没做多少（谦虚一下），总体来讲这次不是很累，就是蹲着跪着腿有点受不了，是应该好好减肥了。</p>
]]></content>
      <categories>
        <category>生活</category>
        <category>运动</category>
        <category>跑步</category>
        <category>干活</category>
      </categories>
      <tags>
        <tag>生活</tag>
        <tag>小技巧</tag>
        <tag>运动</tag>
        <tag>减肥</tag>
        <tag>跑步</tag>
        <tag>干活</tag>
      </tags>
  </entry>
  <entry>
    <title>在老丈人家的小工记五</title>
    <url>/2020/10/18/%E5%9C%A8%E8%80%81%E4%B8%88%E4%BA%BA%E5%AE%B6%E7%9A%84%E5%B0%8F%E5%B7%A5%E8%AE%B0%E4%BA%94/</url>
    <content><![CDATA[<p>终于回忆起来了，年纪大了写这种东西真的要立马写，不然很容易想不起来，那天应该是 9 月 12 日，也就是上周六，因为我爸也去了，而且娘亲（丈母娘，LD 这么叫，我也就随了她这么叫，当然是背后，当面就叫妈）也在那，早上一到那二爹就给我爸指挥了活，要挖一条院子的出水道，自己想出来的词，因为觉得下水道是竖的，在那稍稍帮了一会会忙，然后我还是比较惯例的跟着 LD 还有娘亲去住的家里，主要是老丈人可能也不太想让我干太累的活，因为上次已经差不多把三楼都整理干净了，然后就是二楼了，二楼说实话我也帮不上什么忙，主要是衣服被子什么的，正好是有张以前小孩子睡过的那种摇篮床，看上去虽然有一些破损，整体还是不错的，所以打算拿过去，我就负责把它拆掉了，比较简单的是只要拧螺丝就行了，但是其实是用了好多好多工具才搞定的，一开始只要螺丝刀就行了，但是因为年代久了，后面的螺帽也有点锈住或者本身就会串着会一起动，所以拿来了个扳手，大部分的其实都被这两个工具给搞定了，但是后期大概还剩下四分之一的时候，有一颗完全锈住，并且螺纹跟之前那些都不一样，但是这个已经是最大的螺丝刀了，也没办法换个大的了，所以又去找来个一字的，因为十字的不是也可以用一字的拧嘛，结果可能是我买的工具箱里的一字螺丝刀太新了，口子那很锋利，直接把螺丝花纹给划掉了，大的小的都划掉，然后真的变成凹进去一个圆柱体了，然后就想能不能隔一层布去拧，然而因为的确是已经变成圆柱体了，布也不太给力，不放弃的我又去找来了个老虎钳，妄图把划掉的螺丝用老虎钳钳住，另一端用扳手拧开螺帽，但是这个螺丝跟螺帽真的是生锈的太严重了，外加上钳不太牢，完全是两边一起转，实在是没办法了，在征得同意之后，直接掰断了，火死了，一颗螺丝折腾得比我拆一张床还久，那天因为早上去的也比较晚了，然后就快吃午饭了，正好想着带一点东西过去，就把一些脸盆，泡脚桶啥的拿过去了，先是去吃了饭，还是在那家快餐店，菜的口味还是依然不错，就是人比较多，我爸旁边都是素菜，都没怎么吃远一点的荤菜，下次要早点去，把荤菜放我爸旁边😄（PS：他们家饭还是依然尴尬，需要等），吃完就开到在修的房子那把东西拿了出来，我爸已经动作很快的打了一小半的地沟了，说实话那玩意真的是很重，我之前把它从三楼拿下来，就觉得这个太重了，这次还要用起来，感觉我的手会分分钟废掉，不过一开始我还是跟着LD去了住的家里，惯例睡了午觉，那天睡得比较踏实，竟然睡了一个小时，醒了想了下，其实LD她们收拾也用不上我（没啥力气活），我还是去帮我爸他们，跟LD说了下就去了在修的老房子那，两位老爹在一起钻地，看着就很累，我连忙上去想换一会他们，因为刚好是钻到混凝土地线，特别难，力道不够就会滑开，用蛮力就是钻进去拔不出来，原理是因为本身浇的时候就是很紧实的，需要边钻边动，那家伙实在是太重了，真的是汗如雨下，基本是三个人轮流来，我是个添乱的，经常卡住，然后把地线，其实就是一条混凝土横梁，里面还有14跟18的钢筋，需要割断，这个割断也是很有技巧，钢筋本身在里面是受到挤压的，直接用切割的，到快断掉的时候就会崩一下，非常危险，还是老丈人比较有经验，要留一点点，然后直接用榔头敲断就好了，本来以为这个是最难的了，结果下面是一块非常大的青基石，而且也是石头跟石头挤一块，边上一点点打钻有点杯水车薪，后来是用那种螺旋的钻，钻四个洞，相对位置大概是个长方形，这样子把中间这个长方形钻出来就比较容易地能拿出来了，后面的也容易搞出来了，后面的其实难度不是特别大了，主要是地沟打好之后得看看高低是不是符合要求的，不能本来是往外排水的反而外面高，这个怎么看就又很有技巧了，一般在地上的只要侧着看一下就好了，考究点就用下水平尺，但是在地下的，不用水平尺，其实可以借助于地沟里正要放进去的水管，放点水进去，看水往哪流就行了，铺好水管后，就剩填埋的活了，不是太麻烦了，那天真的是累到了，打那个混凝土的时候我真的是把我整个人压上去了，不过也挺爽的，有点把平时无处发泄的蛮力发泄出去了。</p>
]]></content>
      <categories>
        <category>生活</category>
        <category>运动</category>
        <category>跑步</category>
        <category>干活</category>
      </categories>
      <tags>
        <tag>生活</tag>
        <tag>小技巧</tag>
        <tag>运动</tag>
        <tag>减肥</tag>
        <tag>跑步</tag>
        <tag>干活</tag>
      </tags>
  </entry>
  <entry>
    <title>在老丈人家的小工记四</title>
    <url>/2020/09/26/%E5%9C%A8%E8%80%81%E4%B8%88%E4%BA%BA%E5%AE%B6%E7%9A%84%E5%B0%8F%E5%B7%A5%E8%AE%B0%E5%9B%9B/</url>
    <content><![CDATA[<h2 id="小工记四"><a href="#小工记四" class="headerlink" title="小工记四"></a>小工记四</h2><p>第四周去的时候让我们去了现在在住的房子里，去三楼整理东西了，蛮多的东西需要收拾整理，有些需要丢一下，以前往往是把不太要用的东西就放三楼了，但是后面就不会再去收拾整理，LD 跟丈母娘负责收拾，我不太知道哪些还要的，哪些不要了，而且本来也不擅长这种收拾🤦‍♂️，然后就变成她们收拾出来废纸箱，我负责拆掉，压平，这时候终于觉得体重还算是有点作用，总体来说这个事情我其实也不擅长，不擅长的主要是捆起来，可能我总是小题大做，因为纸箱大小不一，如果不做一下分类，然后把大的折小一些的话，直接绑起来，容易拎起来就散掉了，而且一些鞋盒子这种小件的纸盒会比较薄，冰箱这种大件的比较厚，厚的比较不容易变形，需要大力踩踏，而且扎的时候需要用体重压住捆实了之后那样子才是真的捆实的，不然待会又是松松垮垮容易滑出来散架，因为压住了捆好后，下来了之后箱子就会弹开了把绳子崩紧实，感觉又是掌握到生活小技巧了😃，我这里其实比较单调无聊，然后 LD 那可以说非常厉害了，一共理出来 11 把旧电扇，还有好多没用过全新的不锈钢脸盆大大小小的，感觉比店里在卖的还多，还有是有比较多小时候的东西，特别多小时候的衣服，其实这种对我来说最难了，可能需要读一下断舍离，蛮多东西都舍不得扔，但是其实是没啥用了，然后还占地方，这天应该算是比较轻松的一天了，上午主要是把收拾出来要的和不要的搬下楼，然后下午要去把纸板给卖掉。中午还是去小快餐店吃的，在住的家里理东西还有个好处就是中午吃完饭可以小憩一下，因为我个人是非常依赖午休的，不然下午完全没精神，而且心态也会比较烦躁，一方面是客观的的确比较疲惫，另一方面应该主观心理作用也有点影响，就像上班的时候也是觉得不午睡就会很难受，心理作用也有一点，不过总之能睡还是睡一会，真的没办法就心态好点，吃完午饭之后我们就推着小平板车去收废品的地方卖掉了上午我收拾捆起来的纸板，好像卖了一百多，都是直接过地磅了，不用一捆一捆地称，不过有个小插曲，那里另外一个大爷在倒他的三轮车的时候撞了我一下，还好车速慢，屁股上肉垫后，接下来就比较麻烦了，是LD 她们两姐妹从小到大的书，也要去卖掉，小平板车就载不下了，而且着实也不太好推，轮子不太平，导致推着很累，书有好多箱，本来是想去亲戚家借电动三轮车，因为不会开摩托的那种，摩托的那种 LD 邻居家就有，可是到了那发现那个也是很大，而且刹车是用脚踩的那种，俺爹不太放心，就说第二天周日他有空会帮忙去载了卖掉的，然后比较搞笑的来了，丈母娘看错了时间，以为已经快五点了，就让我们顺便在车里带点东西去在修的房子，放到那边三楼去，到了那还跟老丈人说已经这么迟了要赶紧去菜场买菜了，结果我们回来以后才发现看错了一个小时🤦‍♂️。<br>前面可以没提，前三周去的我们一般就周六去一天，然后周日因为要早点回杭州，而且可能想让我们周日能休息下，但是这周就因为周日的时候我爸要去帮忙载书，然后 LD 姐姐也会过来收拾东西，我们周日就又去整理收拾了，周日由于俺爹去的很早，我过去的时候书已经木有了，主要是去收拾东西了，把一些有用没用的继续整理，基本上三楼的就处理完毕了，舒了一大口气，毕竟让丈母娘一个人收拾实在是太累了，但是要扔掉的衣服比较棘手，附近知道的青蛙回收桶被推倒了，其他地方也不知道哪里有，我们就先载了一些东西去在修的房子那，然后去找青蛙桶，结果一个小区可以进，但是已经满了，另一个不让进，后来只能让 LD 姐姐带去她们小区扔了，塞了满满一车。因为要赶回杭州的车就没有等我爸一起回来，他还在那帮忙搞卫生间的墙缝。<br>虽然这两天不太热，活也不算很吃力，不过我这个体重和易出汗的体质，还是让短袖不知道湿透了多少次，灌了好多水和冰红茶（下午能提提神），回来周一早上称体重也比较喜人，差一点就达到阶段目标，可以想想去哪里吃之前想好的烤肉跟火锅了（估计吃完立马回到解放前）。</p>
]]></content>
      <categories>
        <category>生活</category>
        <category>运动</category>
        <category>跑步</category>
        <category>干活</category>
      </categories>
      <tags>
        <tag>生活</tag>
        <tag>小技巧</tag>
        <tag>运动</tag>
        <tag>减肥</tag>
        <tag>跑步</tag>
        <tag>干活</tag>
      </tags>
  </entry>
  <entry>
    <title>寄生虫观后感</title>
    <url>/2020/03/01/%E5%AF%84%E7%94%9F%E8%99%AB%E8%A7%82%E5%90%8E%E6%84%9F/</url>
    <content><![CDATA[<p>寄生虫这部电影在获得奥斯卡之前就有关注了，豆瓣评分很高，一开始看到这个片名以为是像《铁线虫入侵》那种灾难片，后来看到男主，宋康昊，也是老面孔了，从高中时候在学校操场组织看的《汉江怪物》，有点二的感觉，后来在大学寝室电脑上重新看的时候，室友跟我说是韩国国宝级演员，真人不可貌相，感觉是个呆子的形象。</p>
<p>但是你说这不是个灾难片，而是个反映社会问题的，就业比较容易往这个方向猜，只是剧情会是怎么样的，一时也没啥头绪，后来不知道哪里看了下一个剧情透露，是一个穷人给富人做家教，然后把自己一家都带进富人家，如果是这样的话可能会把这个怎么带进去作为一个主线，不过事实告诉我，这没那么重要，从第一步朋友的介绍，就显得无比顺利，要去当家教了，作为一个穷成这样的人，瞬间转变成一个衣着得体，言行举止都没让富人家看出破绽的延世大学学生，这真的挺难让人理解，所谓江山易改，本性难移，还有就是这人也正好有那么好能力去辅导，并且诡异的是，多惠也是瞬间就喜欢上了男主，多惠跟将男主介绍给她做家教，也就是多惠原来的家教敏赫，应该也有不少的相处时间，这变了有点大了吧，当然这里也可能因为时长需要，如果说这一点是因为时长，那可能我所有的槽点都是因为这个吧，因为我理解的应该是把家里的人如何一步步地带进富人家，这应该是整个剧情的一个需要更多铺垫去克服这个矛盾点，有时候也想过如果我去当导演，是能拍出个啥，没这个机会，可能有也会是很扯淡的，当然这也不能阻拦我谈谈对这个点的一些看法，毕竟评价一台电冰箱不是说我必须得自己会制冷对吧，这大概是我觉得这个电影的第一个槽点，接下去接二连三的，就是我说的这个最核心的矛盾点，不知道谁说过，这种影视剧应该是源自于生活又高于生活，越是好的作品，越要接近生活，这样子才更能有感同身受。</p>
<p>接下去的点是金基宇介绍金基婷去给多颂当美术家教，这一步又是我理解的败笔吧，就怎么说呢，没什么铺垫，突然从一个社会底层的穷姑娘，转变成一个气场爆表，把富人家太太唬得一愣一愣的，如果说富太太是比较简单无脑的，那富人自己应该是比较有见识而且是做 IT 的，给自己儿子女儿做家教的，查查底细也很正常吧，但是啥都没有，然后呢，她又开始耍司机的心机了，真的是莫名其妙了，司机真的很惨，窈窕淑女君子好逑，而且这个操作也让我摸不着头脑，这是多腹黑并且有经验才会这么操作，脱内裤真的是让我看得一愣愣的，更看得我一愣一愣的，富人竟然也完全按着这个思路去想了，完全没有别的可能呢，甚至可以去查下行车记录仪或者怎样的，或者有没有毛发体液啥的去检验下，毕竟金基婷也乘坐过这辆车，但是最最让我不懂的还是脱内裤这个操作，究竟是什么样的人才会的呢，值得思考。</p>
<p>金基泽和忠淑的点也是比较奇怪，首先是金基泽，引起最后那个杀人事件的一个由头，大部分观点都是人为朴社长在之前跟老婆啪啪啪的时候说金基泽的身上有股乘地铁的人的味道，简而言之就是穷人的味道，还有去雯光丈夫身下拿钥匙是对金基泽和雯光丈夫身上的味道的鄙夷，可是这个原因真的站不住脚，即使是同样经济水平，如果身上有比较重的异味，背后讨论下，或者闻到了比较重的味道，有不适的表情和动作很正常吧，像雯光丈夫，在地下室里呆了那么久，身上有异味并且比较重太正常了，就跟在厕所呆久了不会觉得味道大，但是从没味道的地方一进有点味道的厕所就会觉得异样，略尴尬的理由；再说忠淑呢，感觉是太厉害了，能胜任这么一家有钱人的各种挑剔的饮食口味要求的保姆职位，也是让人看懵逼了，看到了不禁想到一个问题，这家人开头是那么地穷，不堪，突然转变成这么地像骗子家族，如果有这么好的骗人能力，应该不会到这种地步吧，如果真的是那么穷，没能力，没志气，又怎么会突然变成这么厉害呢，一家人各司其职，把富人家唬得团团转，而这个前提是，这些人的确能胜任这四个位置，这就是我非常不能理解的点。</p>
<p>然后说回这个标题，寄生虫，不知道是不是翻译过来不准确，如果真的是叫寄生虫的话，这个寄生虫智商未免也太低了，没有像新冠那样机制，致死率低一点，传染能力强一点，潜伏期也能传染，这个寄生虫第一次受到免疫系统的攻击就自爆了；还有呢，作为一个社会比较低层的打工者，乡下人，对这个审题也是不太审的清，是指这一家人是社会的寄生虫，不思进取，并且死的应该，富人是傻白甜，又有钱又善良，这是给有钱人洗地了还是啥，这个奥斯卡真不知道是怎么得的，总觉得奥斯卡，甚至低一点，豆瓣，得奖的，评分高的都是被一群“精英党”把持的，有黑人主角的，得分高；有同性恋的，得分高；结局惨的，得分高；看不懂的，得分高；就像肖申克的救赎，真不知道是哪里好了，最近看了关于明朝那些事的三杨，杨溥的经历应该比这个厉害吧，可是外国人看不懂，就像外国人不懂中国为什么有反分裂国家法，经历了鸦片战争，八国联军，抗日战争等等，其实跟外国对于黑人的权益的问题，因为有南北战争，所以极度重视这个问题，相应的中国也有自己的历史，请理解。</p>
<p>简而言之我对寄生虫的评分大概 5~6 分吧。</p>
]]></content>
      <categories>
        <category>生活</category>
        <category>影评</category>
        <category>2020</category>
      </categories>
      <tags>
        <tag>生活</tag>
        <tag>影评</tag>
        <tag>寄生虫</tag>
      </tags>
  </entry>
  <entry>
    <title>我是如何走上跑步这条不归路的</title>
    <url>/2020/07/26/%E6%88%91%E6%98%AF%E5%A6%82%E4%BD%95%E8%B5%B0%E4%B8%8A%E8%B7%91%E6%AD%A5%E8%BF%99%E6%9D%A1%E4%B8%8D%E5%BD%92%E8%B7%AF%E7%9A%84/</url>
    <content><![CDATA[<p>这周因为没有准备技术方面的内容加之之前有想分享下我和跑步的一些事情，我从小学开始就是个体育渣，因为体重大非常胖，小学的时候要做仰卧起坐，基本是一个都起不来，然后那时候跑步也是要我命那种，跟另外一个比较胖的同学在跑步队尾苟延残喘，只有立定跳远还行。</p>
<p>时光飞逝，我在初中高中的时候因为爱打篮球，以为自己体质已经有了质的变化，所以在体育课跑步的时候妄图跟一位体育非常好的同学一起跑，结果跟的快断气了，最终还是确认了自己是个体育渣，特别是到了大学的第一次体测跑一千米，跑完直接吐了，一则是大学太宅不运动，二则的确是底子不好。那么怎么会去跑步了呢，其实也没什么特殊的原因，就是工作以后因为运动得更少，体质差，而且越来越胖，所以就想运动下，加之跑步也是我觉得成本最低的运动了，刚好那时候17 年租的地方附近小区周围的路车不太多，一圈刚好一公里多，就觉得开始跑跑看，其实想想以前觉得一千米是非常远的，学校塑胶跑道才 400 米，一千米要两圈半，太难了，但是后来在这个小区周围跑的时候好像跑了一圈以后还能再跑一点，最后跑了两圈，可把自己牛坏了，我都能跑两千米了，哈哈，这是个什么概念呢，大学里最让我绝望的两项体育相关的内容就是一千米和十二分钟跑，一千米把我跑吐了，十二分钟跑及格五圈半也能让我跑完花一周时间恢复以及提前一周心理压力爆炸，虽然我那时候跑的不快，但是已经能跑两千米了，瞬间让自己自信心爆炸，并且跑完步出完汗的感觉是非常棒的，毕竟吃奶茶鸡排都能心安理得了，谁叫我跑步了呢😄，其实现在回去看，那时候跑得还算快的，因为还比较瘦，现在要跑得那么快心跳就太快了，关于心跳什么的后面说，开始建立起自信心之后，对跑步这件事就开始不那么排斥跟害怕了，毕竟我能跑两千米了，然后试试三公里，哇，也可以了呢，三公里是什么概念呢，我大学里跑过最多的一次是十二分钟跑五圈半还是六圈，也就是两公里多，不到三公里，几乎是生涯最长了，一时间产生了一些我可能是个被埋没的运动天才的错觉，其实细想下也能明白，只是速度足够慢了就能跑多一点，毕竟提测一千米是要跑进四分钟才及格，自己跑的时候一千米跑六分多钟已经算不慢了（对我自己来说），但是即使是这样还是对把跑步坚持下去这件事有了很大的正面激励作用，并且由于那时候上下班骑车，整个体重控制的比较理想，导致一时间误会跑步就能非常快的减肥（其实这是我跑步历程中比较大的误区之一），因为会在跑步前后称下体重，如果跑个五公里（后面可以跑五公里了），可能体重就能降 0.5 千克，但实际上这只是这五公里跑步身体流失的水分，喝杯水就回来了，那时候能控制体重主要是骑车跟跑步一起的作用，并且工作压力相对来讲比较小，没有过劳肥。</p>
<p>后面其实跑步慢慢变得一个比较习惯的运动了，从三公里，到五公里，到七公里，再到十公里，十公里差不多对我来说是个坎，一直还不能比较轻松的跑十公里，可能近一两年好了一些（原谅我只是跟自己比较，跟那些大神比差得不知道多远），其实对我来说每次都是个突破，因为其实与他人比较没有特别大意义，比较顶尖的差得太远，比较普通的也不行，都会打击自信心，比较比我差的就更没意义了，所以其实能挑战自己，能把自己的上限提高才是最有意义的，这也是我看着朋友圈里的一些大神的速度除了佩服赞叹之外没什么其他的惭愧或者说嫌弃自己的感觉（阿 Q 精神😄）。</p>
<p>一直感性地觉得，跑步能解压，跑完浑身汗，有种把身体的负能量都排出去的感觉，也把吃太多的罪恶感排解掉了🤦‍♂️，之前朋友有看一本书，书名差不多叫越跑越接近自己，这个也是我觉得挺准确的一句话，当跑到接近极限了，还想再继续再跑一点，再跑一点就能突破自己上一次的最远记录了，再跑一点就能又一次突破自己了，成人以后，毕业以后，进入社会以后，世事总是难以件件顺遂，磕磕绊绊的往前走，总觉得要崩溃了，但是还是得坚持，再熬一下，再拼一下，可能还是失败，但人生呢，运气好的人和事总是小概率的，唯有面对挫折，还是日拱一卒，来日方长，我们再坚持下，没准下一次，没准再跑一会，就能突破自己，达到新的境界。</p>
<p>另外个人后期对跑步的一些知识和理解也变得深入一些，比如伤膝盖，其实跑步的确伤膝盖，需要做一些准备和防护，最好的是适合自己的跑鞋和比较好的路（最好的是塑胶跑道了），也要注意热身跟跑后的拉伸（虽然我做的很差），还有就是注意心率，每个人有自己的适宜心率，我这就不冒充科普达人了，可以自行搜索关键字，先说到这吧~</p>
]]></content>
      <categories>
        <category>生活</category>
        <category>运动</category>
        <category>跑步</category>
      </categories>
      <tags>
        <tag>生活</tag>
        <tag>运动</tag>
        <tag>减肥</tag>
        <tag>跑步</tag>
      </tags>
  </entry>
  <entry>
    <title>看完了扫黑风暴,聊聊感想</title>
    <url>/2021/10/24/%E7%9C%8B%E5%AE%8C%E4%BA%86%E6%89%AB%E9%BB%91%E9%A3%8E%E6%9A%B4-%E8%81%8A%E8%81%8A%E6%84%9F%E6%83%B3/</url>
    <content><![CDATA[<p>一直在想这篇怎么写，看了这部剧其实对我的一些观念是有影响的，应该是在 9 月份就看完了，到现在可能才会稍微平静一点，一开始是没有想看这部剧，因为同期有一部差不多同名的电影，被投诉了对湖南埋尸案家属伤害很大，我以为就是投诉的这部电视剧，后来同事跟我说不是，所以就想着看一下，但是没有马上看，因为一直不喜欢追这种比较纠结的剧，当时看人民的名义，就是后面等不了了直接看了小说，所以差不多是等到更完了才看的。</p>
<p>尝试保持一个比较冷静的状态来聊聊，在看的时候有一点感想就是如果要剧里的坏人排个名，因为明眼看都是孙兴是个穷凶极恶的坏人，干尽了坏事，而且可能是演员表演地好，让人真的恨的牙痒痒，但是更多地还是停留在那些剧情中的表现和他的表情，其实对应的真实案例有更多的，这里尽量不展开，有兴趣可以自行搜索关键字，所以其实我想排个名的话，孙兴的母亲应该是我心目中是造成这个结果的比较大占比的始作俑者，因为是方方面面的，包括对林汉的栽赃迫害，最后串起来是因为他看到了孙兴又出来了，就是那句老话，撒了一个谎以后就要用无数个谎来圆，贺芸为了孙兴，作了第一个恶以后就用了一系列的丧心病狂的操作来保护孙兴，而且这之后所做的事情一件比一件可怕，并且如果不是督导组各种想方设法地去破解谜题，这个事情还可以一直被通过各种操作瞒下去，而孙兴还可以继续地为虎作伥，当然其他的包括高明远以及后面的王政，当然是为了这个操作也提供的各种方式的帮助，甚至是主导了这些操作，但是这里贺芸还是在这个位子上能够通过权力做出非常关键的动作，包括栽赃林汉，并且搞掉了李成阳。其中还有一点是我对剧情设计的质疑，也是我前面提到过一点，因为里面孙兴好像是很爱他的母亲贺芸，似乎想表达的是孙兴作的恶是因为得不到母爱，并且个人感觉如果是一个比较敬爱自己母亲的儿子，似乎应该有所畏惧，对他的行为也会有所限制，不应该变成这样一个无恶不作的恶霸，这也是我一直以来的观点，很多人作恶太多可能是因为没有信仰，不管是信基督耶稣还是信道教佛教，总归有一些制约，当然不是说就绝对不会作恶，只是偏向于有所畏惧敬畏，除了某绿哈。</p>
<p>而对于其他的人感觉演技都不错，只是最后有一些虎头蛇尾吧，不知道是不是审核的原因，也不细说了怕被请喝茶，还有提一点就是麦佳的这个事情，她其实是里面很惨的一个人，把高明远当成最亲近的人，而其实真相令人感觉不寒而栗，杀父杀母的仇人，对于麦佳这个演员，一直觉得印象深刻，后来才想起来就是在爱情公寓里演被关谷救了要以身相遇的那个女孩，长相其实蛮令人印象深刻的，但好像也一直不温不火，不过也不能说演技很好吧，只是在这里演的任务真的是很可怜了，剧情设计里也应该是个很重要的串联人物，最终被高明远献给了大佬，这里扯开一点，好像有的观点说贺芸之前也是这样的，只是一种推测了。</p>
<p>看完这部剧其实有很多想说的，但是也为了不被请喝茶，尽量少说了，只想说珍爱生命，还是自己小心吧</p>
]]></content>
      <categories>
        <category>生活</category>
      </categories>
      <tags>
        <tag>生活</tag>
        <tag>影评</tag>
      </tags>
  </entry>
  <entry>
    <title>聊一下 RocketMQ 的消息存储之 MMAP</title>
    <url>/2021/09/04/%E8%81%8A%E4%B8%80%E4%B8%8B-RocketMQ-%E7%9A%84%E6%B6%88%E6%81%AF%E5%AD%98%E5%82%A8/</url>
    <content><![CDATA[<p>这是个很大的话题了，可能会分成两部分说，第一部分就是所谓的零拷贝 ( zero-copy )，这一块其实也不新鲜，我对零拷贝的概念主要来自<a href="https://www.linuxjournal.com/article/6345">这篇文章</a>，个人感觉写得非常好，在 rocketmq 中，最大的一块存储就是消息存储，也就是 CommitLog ，当然还有 ConsumeQueue 和 IndexFile，以及其他一些文件，CommitLog 的存储是以一个 1G 大小的文件作为存储单位，写完了就再建一个，那么如何提高这 1G 文件的读写效率呢，就是 mmap，传统意义的读写文件，read，write 都需要由系统调用，来回地在用户态跟内核态进行拷贝切换，</p>
<pre class="line-numbers language-c" data-language="c"><code class="language-c"><span class="token function">read</span><span class="token punctuation">(</span>file<span class="token punctuation">,</span> tmp_buf<span class="token punctuation">,</span> len<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">write</span><span class="token punctuation">(</span>socket<span class="token punctuation">,</span> tmp_buf<span class="token punctuation">,</span> len<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>



<p><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/vms95Z.jpg" alt="vms95Z"></p>
<p>如上面的图显示的，要在用户态跟内核态进行切换，数据还需要在内核缓冲跟用户缓冲之间拷贝多次，</p>
<blockquote>
<ol>
<li>第一步是调用 read，需要在用户态切换成内核态，<a href="https://en.wikipedia.org/wiki/Direct_memory_access">DMA</a>模块从磁盘中读取文件，并存储在内核缓冲区，相当于是第一次复制</li>
<li>数据从内核缓冲区被拷贝到用户缓冲区，read 调用返回，伴随着内核态又切换成用户态，完成了第二次复制</li>
<li>然后是write 写入，这里也会伴随着用户态跟内核态的切换，数据从用户缓冲区被复制到内核空间缓冲区，完成了第三次复制，这次有点不一样的是数据不是在内核缓冲区了，会复制到 socket buffer 中。</li>
<li>write 系统调用返回，又切换回了用户态，然后数据由 DMA 拷贝到协议引擎。</li>
</ol>
</blockquote>
<p>如此就能看出其实默认的读写操作代价是非常大的，而在 rocketmq 等高性能中间件中都有使用的零拷贝技术，其中 rocketmq 使用的是 mmap</p>
<h3 id="mmap"><a href="#mmap" class="headerlink" title="mmap"></a>mmap</h3><p>mmap基于 OS 的 <a href="https://en.wikipedia.org/wiki/Mmap">mmap</a> 的内存映射技术，通过<a href="https://en.wikipedia.org/wiki/Memory_management_unit">MMU</a> 映射文件，将文件直接映射到用户态的内存地址，使得对文件的操作不再是 write/read,而转化为直接对内存地址的操作，使随机读写文件和读写内存相似的速度。</p>
<blockquote>
<p>mmap 把文件映射到用户空间里的虚拟内存，省去了从内核缓冲区复制到用户空间的过程，文件中的位置在虚拟内存中有了对应的地址，可以像操作内存一样操作这个文件，这样的文件读写文件方式少了数据从内核缓存到用户空间的拷贝，效率很高。</p>
</blockquote>
<pre class="line-numbers language-c" data-language="c"><code class="language-c">tmp_buf <span class="token operator">=</span> <span class="token function">mmap</span><span class="token punctuation">(</span>file<span class="token punctuation">,</span> len<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">write</span><span class="token punctuation">(</span>socket<span class="token punctuation">,</span> tmp_buf<span class="token punctuation">,</span> len<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/I68mFx.jpg" alt="I68mFx"></p>
<blockquote>
<p>第一步：mmap系统调用使得文件内容被DMA引擎复制到内核缓冲区。然后该缓冲区与用户进程共享，在内核和用户内存空间之间不进行任何拷贝。</p>
<p>第二步：写系统调用使得内核将数据从原来的内核缓冲区复制到与套接字相关的内核缓冲区。</p>
<p>第三步：第三次拷贝发生在DMA引擎将数据从内核套接字缓冲区传递给协议引擎时。</p>
<p>通过使用mmap而不是read，我们将内核需要拷贝的数据量减少了一半。当大量的数据被传输时，这将有很好的效果。然而，这种改进并不是没有代价的；在使用mmap+write方法时，有一些隐藏的陷阱。例如当你对一个文件进行内存映射，然后在另一个进程截断同一文件时调用写。你的写系统调用将被总线错误信号SIGBUS打断，因为你执行了一个错误的内存访问。该信号的默认行为是杀死进程并dumpcore–这对网络服务器来说不是最理想的操作。</p>
<p>有两种方法可以解决这个问题。</p>
<p>第一种方法是为SIGBUS信号安装一个信号处理程序，然后在处理程序中简单地调用返回。通过这样做，写系统调用会返回它在被打断之前所写的字节数，并将errno设置为成功。让我指出，这将是一个糟糕的解决方案，一个治标不治本的解决方案。因为SIGBUS预示着进程出了严重的问题，所以不鼓励使用这种解决方案。</p>
<p>第二个解决方案涉及内核的文件租赁（在Windows中称为 “机会锁”）。这是解决这个问题的正确方法。通过在文件描述符上使用租赁，你与内核在一个特定的文件上达成租约。然后你可以向内核请求一个读/写租约。当另一个进程试图截断你正在传输的文件时，内核会向你发送一个实时信号，即RT_SIGNAL_LEASE信号。它告诉你内核即将终止你对该文件的写或读租约。在你的程序访问一个无效的地址和被SIGBUS信号杀死之前，你的写调用会被打断了。写入调用的返回值是中断前写入的字节数，errno将被设置为成功。下面是一些示例代码，显示了如何从内核中获得租约。</p>
<pre class="line-numbers language-c" data-language="c"><code class="language-c"><span class="token keyword">if</span><span class="token punctuation">(</span><span class="token function">fcntl</span><span class="token punctuation">(</span>fd<span class="token punctuation">,</span> F_SETSIG<span class="token punctuation">,</span> RT_SIGNAL_LEASE<span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token function">perror</span><span class="token punctuation">(</span><span class="token string">"kernel lease set signal"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">/* l_type can be F_RDLCK F_WRLCK */</span>
<span class="token keyword">if</span><span class="token punctuation">(</span><span class="token function">fcntl</span><span class="token punctuation">(</span>fd<span class="token punctuation">,</span> F_SETLEASE<span class="token punctuation">,</span> l_type<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
    <span class="token function">perror</span><span class="token punctuation">(</span><span class="token string">"kernel lease set type"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></blockquote>
]]></content>
      <categories>
        <category>MQ</category>
        <category>RocketMQ</category>
        <category>消息队列</category>
      </categories>
      <tags>
        <tag>MQ</tag>
        <tag>消息队列</tag>
        <tag>RocketMQ</tag>
      </tags>
  </entry>
  <entry>
    <title>聊一下 RocketMQ 的消息存储三</title>
    <url>/2021/10/03/%E8%81%8A%E4%B8%80%E4%B8%8B-RocketMQ-%E7%9A%84%E6%B6%88%E6%81%AF%E5%AD%98%E5%82%A8%E4%B8%89/</url>
    <content><![CDATA[<p>ConsumeQueue 其实是定位到一个 topic 下的消息在 CommitLog 下的偏移量，它也是固定大小的</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">// ConsumeQueue file size,default is 30W</span>
<span class="token keyword">private</span> <span class="token keyword">int</span> mapedFileSizeConsumeQueue <span class="token operator">=</span> <span class="token number">300000</span> <span class="token operator">*</span> <span class="token class-name">ConsumeQueue</span><span class="token punctuation">.</span>CQ_STORE_UNIT_SIZE<span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">final</span> <span class="token keyword">int</span> CQ_STORE_UNIT_SIZE <span class="token operator">=</span> <span class="token number">20</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p>所以文件大小是5.7M 左右</p>
<p><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/5udpag.png" alt="5udpag"></p>
<p>ConsumeQueue 的构建是通过<code>org.apache.rocketmq.store.DefaultMessageStore.ReputMessageService</code>运行后的 doReput 方法，而启动是的 reputFromOffset 则是通过<code>org.apache.rocketmq.store.DefaultMessageStore#start</code>中下面代码设置并启动</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"[SetReputOffset] maxPhysicalPosInLogicQueue=&#123;&#125; clMinOffset=&#123;&#125; clMaxOffset=&#123;&#125; clConfirmedOffset=&#123;&#125;"</span><span class="token punctuation">,</span>
                maxPhysicalPosInLogicQueue<span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>commitLog<span class="token punctuation">.</span><span class="token function">getMinOffset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>commitLog<span class="token punctuation">.</span><span class="token function">getMaxOffset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>commitLog<span class="token punctuation">.</span><span class="token function">getConfirmOffset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>reputMessageService<span class="token punctuation">.</span><span class="token function">setReputFromOffset</span><span class="token punctuation">(</span>maxPhysicalPosInLogicQueue<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>reputMessageService<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p>看一下 doReput 的逻辑</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">doReput</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>reputFromOffset <span class="token operator">&lt;</span> <span class="token class-name">DefaultMessageStore</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>commitLog<span class="token punctuation">.</span><span class="token function">getMinOffset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token string">"The reputFromOffset=&#123;&#125; is smaller than minPyOffset=&#123;&#125;, this usually indicate that the dispatch behind too much and the commitlog has expired."</span><span class="token punctuation">,</span>
                    <span class="token keyword">this</span><span class="token punctuation">.</span>reputFromOffset<span class="token punctuation">,</span> <span class="token class-name">DefaultMessageStore</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>commitLog<span class="token punctuation">.</span><span class="token function">getMinOffset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>reputFromOffset <span class="token operator">=</span> <span class="token class-name">DefaultMessageStore</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>commitLog<span class="token punctuation">.</span><span class="token function">getMinOffset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
            <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">boolean</span> doNext <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">isCommitLogAvailable</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> doNext<span class="token punctuation">;</span> <span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>

                <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">DefaultMessageStore</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getMessageStoreConfig</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">isDuplicationEnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
                    <span class="token operator">&amp;&amp;</span> <span class="token keyword">this</span><span class="token punctuation">.</span>reputFromOffset <span class="token operator">>=</span> <span class="token class-name">DefaultMessageStore</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getConfirmOffset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">break</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>

              <span class="token comment">// 根据偏移量获取消息</span>
                <span class="token class-name">SelectMappedBufferResult</span> result <span class="token operator">=</span> <span class="token class-name">DefaultMessageStore</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>commitLog<span class="token punctuation">.</span><span class="token function">getData</span><span class="token punctuation">(</span>reputFromOffset<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>result <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                        <span class="token keyword">this</span><span class="token punctuation">.</span>reputFromOffset <span class="token operator">=</span> result<span class="token punctuation">.</span><span class="token function">getStartOffset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

                        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> readSize <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> readSize <span class="token operator">&lt;</span> result<span class="token punctuation">.</span><span class="token function">getSize</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> doNext<span class="token punctuation">;</span> <span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                          <span class="token comment">// 消息校验和转换</span>
                            <span class="token class-name">DispatchRequest</span> dispatchRequest <span class="token operator">=</span>
                                <span class="token class-name">DefaultMessageStore</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>commitLog<span class="token punctuation">.</span><span class="token function">checkMessageAndReturnSize</span><span class="token punctuation">(</span>result<span class="token punctuation">.</span><span class="token function">getByteBuffer</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token keyword">int</span> size <span class="token operator">=</span> dispatchRequest<span class="token punctuation">.</span><span class="token function">getBufferSize</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token operator">-</span><span class="token number">1</span> <span class="token operator">?</span> dispatchRequest<span class="token punctuation">.</span><span class="token function">getMsgSize</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">:</span> dispatchRequest<span class="token punctuation">.</span><span class="token function">getBufferSize</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

                            <span class="token keyword">if</span> <span class="token punctuation">(</span>dispatchRequest<span class="token punctuation">.</span><span class="token function">isSuccess</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                <span class="token keyword">if</span> <span class="token punctuation">(</span>size <span class="token operator">></span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                  <span class="token comment">// 进行分发处理，包括 ConsumeQueue 和 IndexFile</span>
                                    <span class="token class-name">DefaultMessageStore</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">doDispatch</span><span class="token punctuation">(</span>dispatchRequest<span class="token punctuation">)</span><span class="token punctuation">;</span>

                                    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">BrokerRole</span><span class="token punctuation">.</span>SLAVE <span class="token operator">!=</span> <span class="token class-name">DefaultMessageStore</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getMessageStoreConfig</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getBrokerRole</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
                                        <span class="token operator">&amp;&amp;</span> <span class="token class-name">DefaultMessageStore</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>brokerConfig<span class="token punctuation">.</span><span class="token function">isLongPollingEnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                        <span class="token class-name">DefaultMessageStore</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>messageArrivingListener<span class="token punctuation">.</span><span class="token function">arriving</span><span class="token punctuation">(</span>dispatchRequest<span class="token punctuation">.</span><span class="token function">getTopic</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
                                            dispatchRequest<span class="token punctuation">.</span><span class="token function">getQueueId</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> dispatchRequest<span class="token punctuation">.</span><span class="token function">getConsumeQueueOffset</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">,</span>
                                            dispatchRequest<span class="token punctuation">.</span><span class="token function">getTagsCode</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> dispatchRequest<span class="token punctuation">.</span><span class="token function">getStoreTimestamp</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
                                            dispatchRequest<span class="token punctuation">.</span><span class="token function">getBitMap</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> dispatchRequest<span class="token punctuation">.</span><span class="token function">getPropertiesMap</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                                    <span class="token punctuation">&#125;</span>

                                    <span class="token keyword">this</span><span class="token punctuation">.</span>reputFromOffset <span class="token operator">+=</span> size<span class="token punctuation">;</span>
                                    readSize <span class="token operator">+=</span> size<span class="token punctuation">;</span>
                                    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">DefaultMessageStore</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getMessageStoreConfig</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getBrokerRole</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token class-name">BrokerRole</span><span class="token punctuation">.</span>SLAVE<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                        <span class="token class-name">DefaultMessageStore</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>storeStatsService
                                            <span class="token punctuation">.</span><span class="token function">getSinglePutMessageTopicTimesTotal</span><span class="token punctuation">(</span>dispatchRequest<span class="token punctuation">.</span><span class="token function">getTopic</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">incrementAndGet</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                                        <span class="token class-name">DefaultMessageStore</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>storeStatsService
                                            <span class="token punctuation">.</span><span class="token function">getSinglePutMessageTopicSizeTotal</span><span class="token punctuation">(</span>dispatchRequest<span class="token punctuation">.</span><span class="token function">getTopic</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
                                            <span class="token punctuation">.</span><span class="token function">addAndGet</span><span class="token punctuation">(</span>dispatchRequest<span class="token punctuation">.</span><span class="token function">getMsgSize</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                                    <span class="token punctuation">&#125;</span>
                                <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>size <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                    <span class="token keyword">this</span><span class="token punctuation">.</span>reputFromOffset <span class="token operator">=</span> <span class="token class-name">DefaultMessageStore</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>commitLog<span class="token punctuation">.</span><span class="token function">rollNextFile</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>reputFromOffset<span class="token punctuation">)</span><span class="token punctuation">;</span>
                                    readSize <span class="token operator">=</span> result<span class="token punctuation">.</span><span class="token function">getSize</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                                <span class="token punctuation">&#125;</span>
                            <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>dispatchRequest<span class="token punctuation">.</span><span class="token function">isSuccess</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>

                                <span class="token keyword">if</span> <span class="token punctuation">(</span>size <span class="token operator">></span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                    log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"[BUG]read total count not equals msg total size. reputFromOffset=&#123;&#125;"</span><span class="token punctuation">,</span> reputFromOffset<span class="token punctuation">)</span><span class="token punctuation">;</span>
                                    <span class="token keyword">this</span><span class="token punctuation">.</span>reputFromOffset <span class="token operator">+=</span> size<span class="token punctuation">;</span>
                                <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                                    doNext <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
                                    <span class="token comment">// If user open the dledger pattern or the broker is master node,</span>
                                    <span class="token comment">// it will not ignore the exception and fix the reputFromOffset variable</span>
                                    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">DefaultMessageStore</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getMessageStoreConfig</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">isEnableDLegerCommitLog</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">||</span>
                                        <span class="token class-name">DefaultMessageStore</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>brokerConfig<span class="token punctuation">.</span><span class="token function">getBrokerId</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token class-name">MixAll</span><span class="token punctuation">.</span>MASTER_ID<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                        log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"[BUG]dispatch message to consume queue error, COMMITLOG OFFSET: &#123;&#125;"</span><span class="token punctuation">,</span>
                                            <span class="token keyword">this</span><span class="token punctuation">.</span>reputFromOffset<span class="token punctuation">)</span><span class="token punctuation">;</span>
                                        <span class="token keyword">this</span><span class="token punctuation">.</span>reputFromOffset <span class="token operator">+=</span> result<span class="token punctuation">.</span><span class="token function">getSize</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-</span> readSize<span class="token punctuation">;</span>
                                    <span class="token punctuation">&#125;</span>
                                <span class="token punctuation">&#125;</span>
                            <span class="token punctuation">&#125;</span>
                        <span class="token punctuation">&#125;</span>
                    <span class="token punctuation">&#125;</span> <span class="token keyword">finally</span> <span class="token punctuation">&#123;</span>
                        result<span class="token punctuation">.</span><span class="token function">release</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                    doNext <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>分发的逻辑看到这</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">    <span class="token keyword">class</span> <span class="token class-name">CommitLogDispatcherBuildConsumeQueue</span> <span class="token keyword">implements</span> <span class="token class-name">CommitLogDispatcher</span> <span class="token punctuation">&#123;</span>

        <span class="token annotation punctuation">@Override</span>
        <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">dispatch</span><span class="token punctuation">(</span><span class="token class-name">DispatchRequest</span> request<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">final</span> <span class="token keyword">int</span> tranType <span class="token operator">=</span> <span class="token class-name">MessageSysFlag</span><span class="token punctuation">.</span><span class="token function">getTransactionValue</span><span class="token punctuation">(</span>request<span class="token punctuation">.</span><span class="token function">getSysFlag</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">switch</span> <span class="token punctuation">(</span>tranType<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">case</span> <span class="token class-name">MessageSysFlag</span><span class="token punctuation">.</span>TRANSACTION_NOT_TYPE<span class="token operator">:</span>
                <span class="token keyword">case</span> <span class="token class-name">MessageSysFlag</span><span class="token punctuation">.</span>TRANSACTION_COMMIT_TYPE<span class="token operator">:</span>
                    <span class="token class-name">DefaultMessageStore</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">putMessagePositionInfo</span><span class="token punctuation">(</span>request<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">break</span><span class="token punctuation">;</span>
                <span class="token keyword">case</span> <span class="token class-name">MessageSysFlag</span><span class="token punctuation">.</span>TRANSACTION_PREPARED_TYPE<span class="token operator">:</span>
                <span class="token keyword">case</span> <span class="token class-name">MessageSysFlag</span><span class="token punctuation">.</span>TRANSACTION_ROLLBACK_TYPE<span class="token operator">:</span>
                    <span class="token keyword">break</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">putMessagePositionInfo</span><span class="token punctuation">(</span><span class="token class-name">DispatchRequest</span> dispatchRequest<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">ConsumeQueue</span> cq <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">findConsumeQueue</span><span class="token punctuation">(</span>dispatchRequest<span class="token punctuation">.</span><span class="token function">getTopic</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> dispatchRequest<span class="token punctuation">.</span><span class="token function">getQueueId</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        cq<span class="token punctuation">.</span><span class="token function">putMessagePositionInfoWrapper</span><span class="token punctuation">(</span>dispatchRequest<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>真正存储的是在这</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">private</span> <span class="token keyword">boolean</span> <span class="token function">putMessagePositionInfo</span><span class="token punctuation">(</span><span class="token keyword">final</span> <span class="token keyword">long</span> offset<span class="token punctuation">,</span> <span class="token keyword">final</span> <span class="token keyword">int</span> size<span class="token punctuation">,</span> <span class="token keyword">final</span> <span class="token keyword">long</span> tagsCode<span class="token punctuation">,</span>
    <span class="token keyword">final</span> <span class="token keyword">long</span> cqOffset<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>

    <span class="token keyword">if</span> <span class="token punctuation">(</span>offset <span class="token operator">+</span> size <span class="token operator">&lt;=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>maxPhysicOffset<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token string">"Maybe try to build consume queue repeatedly maxPhysicOffset=&#123;&#125; phyOffset=&#123;&#125;"</span><span class="token punctuation">,</span> maxPhysicOffset<span class="token punctuation">,</span> offset<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">this</span><span class="token punctuation">.</span>byteBufferIndex<span class="token punctuation">.</span><span class="token function">flip</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>byteBufferIndex<span class="token punctuation">.</span><span class="token function">limit</span><span class="token punctuation">(</span>CQ_STORE_UNIT_SIZE<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>byteBufferIndex<span class="token punctuation">.</span><span class="token function">putLong</span><span class="token punctuation">(</span>offset<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>byteBufferIndex<span class="token punctuation">.</span><span class="token function">putInt</span><span class="token punctuation">(</span>size<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>byteBufferIndex<span class="token punctuation">.</span><span class="token function">putLong</span><span class="token punctuation">(</span>tagsCode<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>这里也可以看到 ConsumeQueue 的存储格式，</p>
<p><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/AA6Tve.jpg" alt="AA6Tve"></p>
<p>偏移量，消息大小，跟 tag 的 hashCode</p>
]]></content>
      <categories>
        <category>MQ</category>
        <category>RocketMQ</category>
        <category>消息队列</category>
      </categories>
      <tags>
        <tag>MQ</tag>
        <tag>消息队列</tag>
        <tag>RocketMQ</tag>
      </tags>
  </entry>
  <entry>
    <title>聊一下 RocketMQ 的消息存储四</title>
    <url>/2021/10/17/%E8%81%8A%E4%B8%80%E4%B8%8B-RocketMQ-%E7%9A%84%E6%B6%88%E6%81%AF%E5%AD%98%E5%82%A8%E5%9B%9B/</url>
    <content><![CDATA[<p>IndexFile 结构 hash 结构能够通过 key 寻找到对应在 CommitLog 中的位置</p>
<p>IndexFile 的构建则是分发给这个进行处理</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">class</span> <span class="token class-name">CommitLogDispatcherBuildIndex</span> <span class="token keyword">implements</span> <span class="token class-name">CommitLogDispatcher</span> <span class="token punctuation">&#123;</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">dispatch</span><span class="token punctuation">(</span><span class="token class-name">DispatchRequest</span> request<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">DefaultMessageStore</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>messageStoreConfig<span class="token punctuation">.</span><span class="token function">isMessageIndexEnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">DefaultMessageStore</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>indexService<span class="token punctuation">.</span><span class="token function">buildIndex</span><span class="token punctuation">(</span>request<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">buildIndex</span><span class="token punctuation">(</span><span class="token class-name">DispatchRequest</span> req<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">IndexFile</span> indexFile <span class="token operator">=</span> <span class="token function">retryGetAndCreateIndexFile</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>indexFile <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">long</span> endPhyOffset <span class="token operator">=</span> indexFile<span class="token punctuation">.</span><span class="token function">getEndPhyOffset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">DispatchRequest</span> msg <span class="token operator">=</span> req<span class="token punctuation">;</span>
            <span class="token class-name">String</span> topic <span class="token operator">=</span> msg<span class="token punctuation">.</span><span class="token function">getTopic</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">String</span> keys <span class="token operator">=</span> msg<span class="token punctuation">.</span><span class="token function">getKeys</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>msg<span class="token punctuation">.</span><span class="token function">getCommitLogOffset</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&lt;</span> endPhyOffset<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">return</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>

            <span class="token keyword">final</span> <span class="token keyword">int</span> tranType <span class="token operator">=</span> <span class="token class-name">MessageSysFlag</span><span class="token punctuation">.</span><span class="token function">getTransactionValue</span><span class="token punctuation">(</span>msg<span class="token punctuation">.</span><span class="token function">getSysFlag</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">switch</span> <span class="token punctuation">(</span>tranType<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">case</span> <span class="token class-name">MessageSysFlag</span><span class="token punctuation">.</span>TRANSACTION_NOT_TYPE<span class="token operator">:</span>
                <span class="token keyword">case</span> <span class="token class-name">MessageSysFlag</span><span class="token punctuation">.</span>TRANSACTION_PREPARED_TYPE<span class="token operator">:</span>
                <span class="token keyword">case</span> <span class="token class-name">MessageSysFlag</span><span class="token punctuation">.</span>TRANSACTION_COMMIT_TYPE<span class="token operator">:</span>
                    <span class="token keyword">break</span><span class="token punctuation">;</span>
                <span class="token keyword">case</span> <span class="token class-name">MessageSysFlag</span><span class="token punctuation">.</span>TRANSACTION_ROLLBACK_TYPE<span class="token operator">:</span>
                    <span class="token keyword">return</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>

            <span class="token keyword">if</span> <span class="token punctuation">(</span>req<span class="token punctuation">.</span><span class="token function">getUniqKey</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                indexFile <span class="token operator">=</span> <span class="token function">putKey</span><span class="token punctuation">(</span>indexFile<span class="token punctuation">,</span> msg<span class="token punctuation">,</span> <span class="token function">buildKey</span><span class="token punctuation">(</span>topic<span class="token punctuation">,</span> req<span class="token punctuation">.</span><span class="token function">getUniqKey</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>indexFile <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"putKey error commitlog &#123;&#125; uniqkey &#123;&#125;"</span><span class="token punctuation">,</span> req<span class="token punctuation">.</span><span class="token function">getCommitLogOffset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> req<span class="token punctuation">.</span><span class="token function">getUniqKey</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">return</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span>

            <span class="token keyword">if</span> <span class="token punctuation">(</span>keys <span class="token operator">!=</span> <span class="token keyword">null</span> <span class="token operator">&amp;&amp;</span> keys<span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">></span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> keyset <span class="token operator">=</span> keys<span class="token punctuation">.</span><span class="token function">split</span><span class="token punctuation">(</span><span class="token class-name">MessageConst</span><span class="token punctuation">.</span>KEY_SEPARATOR<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> keyset<span class="token punctuation">.</span>length<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token class-name">String</span> key <span class="token operator">=</span> keyset<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">;</span>
                    <span class="token keyword">if</span> <span class="token punctuation">(</span>key<span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">></span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        indexFile <span class="token operator">=</span> <span class="token function">putKey</span><span class="token punctuation">(</span>indexFile<span class="token punctuation">,</span> msg<span class="token punctuation">,</span> <span class="token function">buildKey</span><span class="token punctuation">(</span>topic<span class="token punctuation">,</span> key<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token keyword">if</span> <span class="token punctuation">(</span>indexFile <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                            log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"putKey error commitlog &#123;&#125; uniqkey &#123;&#125;"</span><span class="token punctuation">,</span> req<span class="token punctuation">.</span><span class="token function">getCommitLogOffset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> req<span class="token punctuation">.</span><span class="token function">getUniqKey</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token keyword">return</span><span class="token punctuation">;</span>
                        <span class="token punctuation">&#125;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
            log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"build index error, stop building index"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>配置的数量</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">private</span> <span class="token keyword">boolean</span> messageIndexEnable <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
<span class="token keyword">private</span> <span class="token keyword">int</span> maxHashSlotNum <span class="token operator">=</span> <span class="token number">5000000</span><span class="token punctuation">;</span>
<span class="token keyword">private</span> <span class="token keyword">int</span> maxIndexNum <span class="token operator">=</span> <span class="token number">5000000</span> <span class="token operator">*</span> <span class="token number">4</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>最核心的其实是 IndexFile 的结构和如何写入</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">putKey</span><span class="token punctuation">(</span><span class="token keyword">final</span> <span class="token class-name">String</span> key<span class="token punctuation">,</span> <span class="token keyword">final</span> <span class="token keyword">long</span> phyOffset<span class="token punctuation">,</span> <span class="token keyword">final</span> <span class="token keyword">long</span> storeTimestamp<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>indexHeader<span class="token punctuation">.</span><span class="token function">getIndexCount</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&lt;</span> <span class="token keyword">this</span><span class="token punctuation">.</span>indexNum<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
          <span class="token comment">// 获取 key 的 hash</span>
            <span class="token keyword">int</span> keyHash <span class="token operator">=</span> <span class="token function">indexKeyHashMethod</span><span class="token punctuation">(</span>key<span class="token punctuation">)</span><span class="token punctuation">;</span>
          <span class="token comment">// 计算属于哪个 slot</span>
            <span class="token keyword">int</span> slotPos <span class="token operator">=</span> keyHash <span class="token operator">%</span> <span class="token keyword">this</span><span class="token punctuation">.</span>hashSlotNum<span class="token punctuation">;</span>
          <span class="token comment">// 计算 slot 位置 因为结构是有个 indexHead，主要是分为三段 header，slot 和 index</span>
            <span class="token keyword">int</span> absSlotPos <span class="token operator">=</span> <span class="token class-name">IndexHeader</span><span class="token punctuation">.</span>INDEX_HEADER_SIZE <span class="token operator">+</span> slotPos <span class="token operator">*</span> hashSlotSize<span class="token punctuation">;</span>

            <span class="token class-name">FileLock</span> fileLock <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>

            <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>

                <span class="token comment">// fileLock = this.fileChannel.lock(absSlotPos, hashSlotSize,</span>
                <span class="token comment">// false);</span>
                <span class="token keyword">int</span> slotValue <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>mappedByteBuffer<span class="token punctuation">.</span><span class="token function">getInt</span><span class="token punctuation">(</span>absSlotPos<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>slotValue <span class="token operator">&lt;=</span> invalidIndex <span class="token operator">||</span> slotValue <span class="token operator">></span> <span class="token keyword">this</span><span class="token punctuation">.</span>indexHeader<span class="token punctuation">.</span><span class="token function">getIndexCount</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    slotValue <span class="token operator">=</span> invalidIndex<span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>

                <span class="token keyword">long</span> timeDiff <span class="token operator">=</span> storeTimestamp <span class="token operator">-</span> <span class="token keyword">this</span><span class="token punctuation">.</span>indexHeader<span class="token punctuation">.</span><span class="token function">getBeginTimestamp</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

                timeDiff <span class="token operator">=</span> timeDiff <span class="token operator">/</span> <span class="token number">1000</span><span class="token punctuation">;</span>

                <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>indexHeader<span class="token punctuation">.</span><span class="token function">getBeginTimestamp</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&lt;=</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    timeDiff <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>timeDiff <span class="token operator">></span> <span class="token class-name">Integer</span><span class="token punctuation">.</span>MAX_VALUE<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    timeDiff <span class="token operator">=</span> <span class="token class-name">Integer</span><span class="token punctuation">.</span>MAX_VALUE<span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>timeDiff <span class="token operator">&lt;</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    timeDiff <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>

              <span class="token comment">// 计算索引存放位置，头部 + slot 数量 * slot 大小 + 已有的 index 数量 + index 大小</span>
                <span class="token keyword">int</span> absIndexPos <span class="token operator">=</span>
                    <span class="token class-name">IndexHeader</span><span class="token punctuation">.</span>INDEX_HEADER_SIZE <span class="token operator">+</span> <span class="token keyword">this</span><span class="token punctuation">.</span>hashSlotNum <span class="token operator">*</span> hashSlotSize
                        <span class="token operator">+</span> <span class="token keyword">this</span><span class="token punctuation">.</span>indexHeader<span class="token punctuation">.</span><span class="token function">getIndexCount</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">*</span> indexSize<span class="token punctuation">;</span>
							
                <span class="token keyword">this</span><span class="token punctuation">.</span>mappedByteBuffer<span class="token punctuation">.</span><span class="token function">putInt</span><span class="token punctuation">(</span>absIndexPos<span class="token punctuation">,</span> keyHash<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>mappedByteBuffer<span class="token punctuation">.</span><span class="token function">putLong</span><span class="token punctuation">(</span>absIndexPos <span class="token operator">+</span> <span class="token number">4</span><span class="token punctuation">,</span> phyOffset<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>mappedByteBuffer<span class="token punctuation">.</span><span class="token function">putInt</span><span class="token punctuation">(</span>absIndexPos <span class="token operator">+</span> <span class="token number">4</span> <span class="token operator">+</span> <span class="token number">8</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token keyword">int</span><span class="token punctuation">)</span> timeDiff<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>mappedByteBuffer<span class="token punctuation">.</span><span class="token function">putInt</span><span class="token punctuation">(</span>absIndexPos <span class="token operator">+</span> <span class="token number">4</span> <span class="token operator">+</span> <span class="token number">8</span> <span class="token operator">+</span> <span class="token number">4</span><span class="token punctuation">,</span> slotValue<span class="token punctuation">)</span><span class="token punctuation">;</span>

              <span class="token comment">// 存放的是数量位移，不是绝对位置</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>mappedByteBuffer<span class="token punctuation">.</span><span class="token function">putInt</span><span class="token punctuation">(</span>absSlotPos<span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>indexHeader<span class="token punctuation">.</span><span class="token function">getIndexCount</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

                <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>indexHeader<span class="token punctuation">.</span><span class="token function">getIndexCount</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&lt;=</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">this</span><span class="token punctuation">.</span>indexHeader<span class="token punctuation">.</span><span class="token function">setBeginPhyOffset</span><span class="token punctuation">(</span>phyOffset<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">this</span><span class="token punctuation">.</span>indexHeader<span class="token punctuation">.</span><span class="token function">setBeginTimestamp</span><span class="token punctuation">(</span>storeTimestamp<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>

                <span class="token keyword">this</span><span class="token punctuation">.</span>indexHeader<span class="token punctuation">.</span><span class="token function">incHashSlotCount</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>indexHeader<span class="token punctuation">.</span><span class="token function">incIndexCount</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>indexHeader<span class="token punctuation">.</span><span class="token function">setEndPhyOffset</span><span class="token punctuation">(</span>phyOffset<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>indexHeader<span class="token punctuation">.</span><span class="token function">setEndTimestamp</span><span class="token punctuation">(</span>storeTimestamp<span class="token punctuation">)</span><span class="token punctuation">;</span>

                <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"putKey exception, Key: "</span> <span class="token operator">+</span> key <span class="token operator">+</span> <span class="token string">" KeyHashCode: "</span> <span class="token operator">+</span> key<span class="token punctuation">.</span><span class="token function">hashCode</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">finally</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>fileLock <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                        fileLock<span class="token punctuation">.</span><span class="token function">release</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">IOException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"Failed to release the lock"</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
            log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token string">"Over index file capacity: index count = "</span> <span class="token operator">+</span> <span class="token keyword">this</span><span class="token punctuation">.</span>indexHeader<span class="token punctuation">.</span><span class="token function">getIndexCount</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
                <span class="token operator">+</span> <span class="token string">"; index max num = "</span> <span class="token operator">+</span> <span class="token keyword">this</span><span class="token punctuation">.</span>indexNum<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>具体可以看一下这个简略的示意图<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/kqfruz.png"></p>
]]></content>
      <categories>
        <category>MQ</category>
        <category>RocketMQ</category>
        <category>消息队列</category>
      </categories>
      <tags>
        <tag>MQ</tag>
        <tag>消息队列</tag>
        <tag>RocketMQ</tag>
      </tags>
  </entry>
  <entry>
    <title>聊一下 RocketMQ 的顺序消息</title>
    <url>/2021/08/29/%E8%81%8A%E4%B8%80%E4%B8%8B-RocketMQ-%E7%9A%84%E9%A1%BA%E5%BA%8F%E6%B6%88%E6%81%AF/</url>
    <content><![CDATA[<p>rocketmq 里有一种比较特殊的用法，就是顺序消息，比如订单的生命周期里，在创建，支付，签收等状态轮转中，会发出来对应的消息，这里面就比较需要去保证他们的顺序，当然在处理的业务代码也可以做对应的处理，结合消息重投，但是如果这里消息就能保证顺序性了，那么业务代码就能更好的关注业务代码的处理。</p>
<p>首先有一种情况是全局的有序，比如对于一个 topic 里就得发送线程保证只有一个，内部的 queue 也只有一个，消费线程也只有一个，这样就能比较容易的保证全局顺序性了，但是这里的问题就是完全限制了性能，不是很现实，在真实场景里很多都是比如对于同一个订单，需要去保证状态的轮转是按照预期的顺序来，而不必要全局的有序性。</p>
<p>对于这类的有序性，需要在发送和接收方都有对应的处理，在发送消息中，需要去指定 selector，即<code>MessageQueueSelector</code>，能够以固定的方式是分配到对应的 <code>MessageQueue</code></p>
<p>比如像 RocketMQ 中的示例</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">SendResult</span> sendResult <span class="token operator">=</span> producer<span class="token punctuation">.</span><span class="token function">send</span><span class="token punctuation">(</span>msg<span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">MessageQueueSelector</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token annotation punctuation">@Override</span>
                <span class="token keyword">public</span> <span class="token class-name">MessageQueue</span> <span class="token function">select</span><span class="token punctuation">(</span><span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">MessageQueue</span><span class="token punctuation">></span></span> mqs<span class="token punctuation">,</span> <span class="token class-name">Message</span> msg<span class="token punctuation">,</span> <span class="token class-name">Object</span> arg<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token class-name">Long</span> id <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">Long</span><span class="token punctuation">)</span> arg<span class="token punctuation">;</span>  <span class="token comment">//message queue is selected by #salesOrderID</span>
                    <span class="token keyword">long</span> index <span class="token operator">=</span> id <span class="token operator">%</span> mqs<span class="token punctuation">.</span><span class="token function">size</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">return</span> mqs<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token keyword">int</span><span class="token punctuation">)</span> index<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span><span class="token punctuation">,</span> orderList<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getOrderId</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>而在消费侧有几个点比较重要，首先我们要保证一个 MessageQueue只被一个消费者消费，消费队列存在broker端，要保证 MessageQueue 只被一个消费者消费，那么消费者在进行消息拉取消费时就<strong>必须向mq服务器申请队列锁</strong>，消费者申请队列锁的代码存在于RebalanceService消息队列负载的实现代码中。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">PullRequest</span><span class="token punctuation">></span></span> pullRequestList <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayList</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">PullRequest</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">MessageQueue</span> mq <span class="token operator">:</span> mqSet<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token keyword">this</span><span class="token punctuation">.</span>processQueueTable<span class="token punctuation">.</span><span class="token function">containsKey</span><span class="token punctuation">(</span>mq<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
              <span class="token comment">// 判断是否顺序，如果是顺序消费的，则需要加锁</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>isOrder <span class="token operator">&amp;&amp;</span> <span class="token operator">!</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">lock</span><span class="token punctuation">(</span>mq<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token string">"doRebalance, &#123;&#125;, add a new mq failed, &#123;&#125;, because lock failed"</span><span class="token punctuation">,</span> consumerGroup<span class="token punctuation">,</span> mq<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">continue</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>

                <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">removeDirtyOffset</span><span class="token punctuation">(</span>mq<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token class-name">ProcessQueue</span> pq <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ProcessQueue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">long</span> nextOffset <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">computePullFromWhere</span><span class="token punctuation">(</span>mq<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>nextOffset <span class="token operator">>=</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token class-name">ProcessQueue</span> pre <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>processQueueTable<span class="token punctuation">.</span><span class="token function">putIfAbsent</span><span class="token punctuation">(</span>mq<span class="token punctuation">,</span> pq<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">if</span> <span class="token punctuation">(</span>pre <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"doRebalance, &#123;&#125;, mq already exists, &#123;&#125;"</span><span class="token punctuation">,</span> consumerGroup<span class="token punctuation">,</span> mq<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                        log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"doRebalance, &#123;&#125;, add a new mq, &#123;&#125;"</span><span class="token punctuation">,</span> consumerGroup<span class="token punctuation">,</span> mq<span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token class-name">PullRequest</span> pullRequest <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">PullRequest</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                        pullRequest<span class="token punctuation">.</span><span class="token function">setConsumerGroup</span><span class="token punctuation">(</span>consumerGroup<span class="token punctuation">)</span><span class="token punctuation">;</span>
                        pullRequest<span class="token punctuation">.</span><span class="token function">setNextOffset</span><span class="token punctuation">(</span>nextOffset<span class="token punctuation">)</span><span class="token punctuation">;</span>
                        pullRequest<span class="token punctuation">.</span><span class="token function">setMessageQueue</span><span class="token punctuation">(</span>mq<span class="token punctuation">)</span><span class="token punctuation">;</span>
                        pullRequest<span class="token punctuation">.</span><span class="token function">setProcessQueue</span><span class="token punctuation">(</span>pq<span class="token punctuation">)</span><span class="token punctuation">;</span>
                        pullRequestList<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>pullRequest<span class="token punctuation">)</span><span class="token punctuation">;</span>
                        changed <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                    log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token string">"doRebalance, &#123;&#125;, add new mq failed, &#123;&#125;"</span><span class="token punctuation">,</span> consumerGroup<span class="token punctuation">,</span> mq<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>在申请到锁之后会创建 pullRequest 进行消息拉取，消息拉取部分的代码实现在PullMessageService中，</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getServiceName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">" service started"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">isStopped</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                <span class="token class-name">PullRequest</span> pullRequest <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>pullRequestQueue<span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">pullMessage</span><span class="token punctuation">(</span>pullRequest<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> ignored<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"Pull Message Service Run Method exception"</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>

        log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getServiceName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">" service end"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>消息拉取完后，需要提交到ConsumeMessageService中进行消费，顺序消费的实现为ConsumeMessageOrderlyService，提交消息进行消费的方法为ConsumeMessageOrderlyService#submitConsumeRequest，具体实现如下：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Override</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">submitConsumeRequest</span><span class="token punctuation">(</span>
    <span class="token keyword">final</span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">MessageExt</span><span class="token punctuation">></span></span> msgs<span class="token punctuation">,</span>
    <span class="token keyword">final</span> <span class="token class-name">ProcessQueue</span> processQueue<span class="token punctuation">,</span>
    <span class="token keyword">final</span> <span class="token class-name">MessageQueue</span> messageQueue<span class="token punctuation">,</span>
    <span class="token keyword">final</span> <span class="token keyword">boolean</span> dispathToConsume<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>dispathToConsume<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">ConsumeRequest</span> consumeRequest <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ConsumeRequest</span><span class="token punctuation">(</span>processQueue<span class="token punctuation">,</span> messageQueue<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>consumeExecutor<span class="token punctuation">.</span><span class="token function">submit</span><span class="token punctuation">(</span>consumeRequest<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>构建了一个ConsumeRequest对象，它是个实现了 runnable 接口的类，并提交给了线程池来并行消费，看下顺序消费的ConsumeRequest的run方法实现：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Override</span>
        <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>processQueue<span class="token punctuation">.</span><span class="token function">isDropped</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token string">"run, the message queue not be able to consume, because it's dropped. &#123;&#125;"</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>messageQueue<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">return</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
						<span class="token comment">// 获得 Consumer 消息队列锁，即单个线程独占</span>
            <span class="token keyword">final</span> <span class="token class-name">Object</span> objLock <span class="token operator">=</span> messageQueueLock<span class="token punctuation">.</span><span class="token function">fetchLockObject</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>messageQueue<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">synchronized</span> <span class="token punctuation">(</span>objLock<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
              <span class="token comment">// (广播模式) 或者 (集群模式 &amp;&amp; Broker消息队列锁有效)</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">MessageModel</span><span class="token punctuation">.</span>BROADCASTING<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span><span class="token class-name">ConsumeMessageOrderlyService</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>defaultMQPushConsumerImpl<span class="token punctuation">.</span><span class="token function">messageModel</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
                    <span class="token operator">||</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>processQueue<span class="token punctuation">.</span><span class="token function">isLocked</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> <span class="token operator">!</span><span class="token keyword">this</span><span class="token punctuation">.</span>processQueue<span class="token punctuation">.</span><span class="token function">isLockExpired</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">final</span> <span class="token keyword">long</span> beginTime <span class="token operator">=</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">currentTimeMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                  <span class="token comment">// 循环</span>
                    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">boolean</span> continueConsume <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span> continueConsume<span class="token punctuation">;</span> <span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>processQueue<span class="token punctuation">.</span><span class="token function">isDropped</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                            log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token string">"the message queue not be able to consume, because it's dropped. &#123;&#125;"</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>messageQueue<span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token keyword">break</span><span class="token punctuation">;</span>
                        <span class="token punctuation">&#125;</span>

                      <span class="token comment">// 消息队列分布式锁未锁定，提交延迟获得锁并消费请求</span>
                        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">MessageModel</span><span class="token punctuation">.</span>CLUSTERING<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span><span class="token class-name">ConsumeMessageOrderlyService</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>defaultMQPushConsumerImpl<span class="token punctuation">.</span><span class="token function">messageModel</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
                            <span class="token operator">&amp;&amp;</span> <span class="token operator">!</span><span class="token keyword">this</span><span class="token punctuation">.</span>processQueue<span class="token punctuation">.</span><span class="token function">isLocked</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                            log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token string">"the message queue not locked, so consume later, &#123;&#125;"</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>messageQueue<span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token class-name">ConsumeMessageOrderlyService</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">tryLockLaterAndReconsume</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>messageQueue<span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>processQueue<span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token keyword">break</span><span class="token punctuation">;</span>
                        <span class="token punctuation">&#125;</span>

                      <span class="token comment">// 消息队列分布式锁已经过期，提交延迟获得锁并消费请求</span>
                        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">MessageModel</span><span class="token punctuation">.</span>CLUSTERING<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span><span class="token class-name">ConsumeMessageOrderlyService</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>defaultMQPushConsumerImpl<span class="token punctuation">.</span><span class="token function">messageModel</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
                            <span class="token operator">&amp;&amp;</span> <span class="token keyword">this</span><span class="token punctuation">.</span>processQueue<span class="token punctuation">.</span><span class="token function">isLockExpired</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                            log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token string">"the message queue lock expired, so consume later, &#123;&#125;"</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>messageQueue<span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token class-name">ConsumeMessageOrderlyService</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">tryLockLaterAndReconsume</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>messageQueue<span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>processQueue<span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token keyword">break</span><span class="token punctuation">;</span>
                        <span class="token punctuation">&#125;</span>
												<span class="token comment">// 当前周期消费时间超过连续时长，默认：60s，提交延迟消费请求。默认情况下，每消费1分钟休息10ms。</span>
                        <span class="token keyword">long</span> interval <span class="token operator">=</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">currentTimeMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-</span> beginTime<span class="token punctuation">;</span>
                        <span class="token keyword">if</span> <span class="token punctuation">(</span>interval <span class="token operator">></span> MAX_TIME_CONSUME_CONTINUOUSLY<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                            <span class="token class-name">ConsumeMessageOrderlyService</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">submitConsumeRequestLater</span><span class="token punctuation">(</span>processQueue<span class="token punctuation">,</span> messageQueue<span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token keyword">break</span><span class="token punctuation">;</span>
                        <span class="token punctuation">&#125;</span>
												<span class="token comment">// 获取消费消息。此处和并发消息请求不同，并发消息请求已经带了消费哪些消息。</span>
                        <span class="token keyword">final</span> <span class="token keyword">int</span> consumeBatchSize <span class="token operator">=</span>
                            <span class="token class-name">ConsumeMessageOrderlyService</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>defaultMQPushConsumer<span class="token punctuation">.</span><span class="token function">getConsumeMessageBatchMaxSize</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

                        <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">MessageExt</span><span class="token punctuation">></span></span> msgs <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>processQueue<span class="token punctuation">.</span><span class="token function">takeMessags</span><span class="token punctuation">(</span>consumeBatchSize<span class="token punctuation">)</span><span class="token punctuation">;</span>
                        defaultMQPushConsumerImpl<span class="token punctuation">.</span><span class="token function">resetRetryAndNamespace</span><span class="token punctuation">(</span>msgs<span class="token punctuation">,</span> defaultMQPushConsumer<span class="token punctuation">.</span><span class="token function">getConsumerGroup</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>msgs<span class="token punctuation">.</span><span class="token function">isEmpty</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                            <span class="token keyword">final</span> <span class="token class-name">ConsumeOrderlyContext</span> context <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ConsumeOrderlyContext</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>messageQueue<span class="token punctuation">)</span><span class="token punctuation">;</span>

                            <span class="token class-name">ConsumeOrderlyStatus</span> status <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>

                            <span class="token class-name">ConsumeMessageContext</span> consumeMessageContext <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
                            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">ConsumeMessageOrderlyService</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>defaultMQPushConsumerImpl<span class="token punctuation">.</span><span class="token function">hasHook</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                consumeMessageContext <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ConsumeMessageContext</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                                consumeMessageContext
                                    <span class="token punctuation">.</span><span class="token function">setConsumerGroup</span><span class="token punctuation">(</span><span class="token class-name">ConsumeMessageOrderlyService</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>defaultMQPushConsumer<span class="token punctuation">.</span><span class="token function">getConsumerGroup</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                                consumeMessageContext<span class="token punctuation">.</span><span class="token function">setNamespace</span><span class="token punctuation">(</span>defaultMQPushConsumer<span class="token punctuation">.</span><span class="token function">getNamespace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                                consumeMessageContext<span class="token punctuation">.</span><span class="token function">setMq</span><span class="token punctuation">(</span>messageQueue<span class="token punctuation">)</span><span class="token punctuation">;</span>
                                consumeMessageContext<span class="token punctuation">.</span><span class="token function">setMsgList</span><span class="token punctuation">(</span>msgs<span class="token punctuation">)</span><span class="token punctuation">;</span>
                                consumeMessageContext<span class="token punctuation">.</span><span class="token function">setSuccess</span><span class="token punctuation">(</span><span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                                <span class="token comment">// init the consume context type</span>
                                consumeMessageContext<span class="token punctuation">.</span><span class="token function">setProps</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">HashMap</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">String</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                                <span class="token class-name">ConsumeMessageOrderlyService</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>defaultMQPushConsumerImpl<span class="token punctuation">.</span><span class="token function">executeHookBefore</span><span class="token punctuation">(</span>consumeMessageContext<span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token punctuation">&#125;</span>
														<span class="token comment">// 执行消费</span>
                            <span class="token keyword">long</span> beginTimestamp <span class="token operator">=</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">currentTimeMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token class-name">ConsumeReturnType</span> returnType <span class="token operator">=</span> <span class="token class-name">ConsumeReturnType</span><span class="token punctuation">.</span>SUCCESS<span class="token punctuation">;</span>
                            <span class="token keyword">boolean</span> hasException <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
                            <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                                <span class="token keyword">this</span><span class="token punctuation">.</span>processQueue<span class="token punctuation">.</span><span class="token function">getLockConsume</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// 锁定处理队列</span>
                                <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>processQueue<span class="token punctuation">.</span><span class="token function">isDropped</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                    log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token string">"consumeMessage, the message queue not be able to consume, because it's dropped. &#123;&#125;"</span><span class="token punctuation">,</span>
                                        <span class="token keyword">this</span><span class="token punctuation">.</span>messageQueue<span class="token punctuation">)</span><span class="token punctuation">;</span>
                                    <span class="token keyword">break</span><span class="token punctuation">;</span>
                                <span class="token punctuation">&#125;</span>

                                status <span class="token operator">=</span> messageListener<span class="token punctuation">.</span><span class="token function">consumeMessage</span><span class="token punctuation">(</span><span class="token class-name">Collections</span><span class="token punctuation">.</span><span class="token function">unmodifiableList</span><span class="token punctuation">(</span>msgs<span class="token punctuation">)</span><span class="token punctuation">,</span> context<span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Throwable</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token string">"consumeMessage exception: &#123;&#125; Group: &#123;&#125; Msgs: &#123;&#125; MQ: &#123;&#125;"</span><span class="token punctuation">,</span>
                                    <span class="token class-name">RemotingHelper</span><span class="token punctuation">.</span><span class="token function">exceptionSimpleDesc</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span><span class="token punctuation">,</span>
                                    <span class="token class-name">ConsumeMessageOrderlyService</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>consumerGroup<span class="token punctuation">,</span>
                                    msgs<span class="token punctuation">,</span>
                                    messageQueue<span class="token punctuation">)</span><span class="token punctuation">;</span>
                                hasException <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
                            <span class="token punctuation">&#125;</span> <span class="token keyword">finally</span> <span class="token punctuation">&#123;</span>
                                <span class="token keyword">this</span><span class="token punctuation">.</span>processQueue<span class="token punctuation">.</span><span class="token function">getLockConsume</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  <span class="token comment">// 解锁</span>
                            <span class="token punctuation">&#125;</span>

                            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">null</span> <span class="token operator">==</span> status
                                <span class="token operator">||</span> <span class="token class-name">ConsumeOrderlyStatus</span><span class="token punctuation">.</span>ROLLBACK <span class="token operator">==</span> status
                                <span class="token operator">||</span> <span class="token class-name">ConsumeOrderlyStatus</span><span class="token punctuation">.</span>SUSPEND_CURRENT_QUEUE_A_MOMENT <span class="token operator">==</span> status<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token string">"consumeMessage Orderly return not OK, Group: &#123;&#125; Msgs: &#123;&#125; MQ: &#123;&#125;"</span><span class="token punctuation">,</span>
                                    <span class="token class-name">ConsumeMessageOrderlyService</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>consumerGroup<span class="token punctuation">,</span>
                                    msgs<span class="token punctuation">,</span>
                                    messageQueue<span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token punctuation">&#125;</span>

                            <span class="token keyword">long</span> consumeRT <span class="token operator">=</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">currentTimeMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-</span> beginTimestamp<span class="token punctuation">;</span>
                            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">null</span> <span class="token operator">==</span> status<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                <span class="token keyword">if</span> <span class="token punctuation">(</span>hasException<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                    returnType <span class="token operator">=</span> <span class="token class-name">ConsumeReturnType</span><span class="token punctuation">.</span>EXCEPTION<span class="token punctuation">;</span>
                                <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                                    returnType <span class="token operator">=</span> <span class="token class-name">ConsumeReturnType</span><span class="token punctuation">.</span>RETURNNULL<span class="token punctuation">;</span>
                                <span class="token punctuation">&#125;</span>
                            <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>consumeRT <span class="token operator">>=</span> defaultMQPushConsumer<span class="token punctuation">.</span><span class="token function">getConsumeTimeout</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">*</span> <span class="token number">60</span> <span class="token operator">*</span> <span class="token number">1000</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                returnType <span class="token operator">=</span> <span class="token class-name">ConsumeReturnType</span><span class="token punctuation">.</span>TIME_OUT<span class="token punctuation">;</span>
                            <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">ConsumeOrderlyStatus</span><span class="token punctuation">.</span>SUSPEND_CURRENT_QUEUE_A_MOMENT <span class="token operator">==</span> status<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                returnType <span class="token operator">=</span> <span class="token class-name">ConsumeReturnType</span><span class="token punctuation">.</span>FAILED<span class="token punctuation">;</span>
                            <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">ConsumeOrderlyStatus</span><span class="token punctuation">.</span>SUCCESS <span class="token operator">==</span> status<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                returnType <span class="token operator">=</span> <span class="token class-name">ConsumeReturnType</span><span class="token punctuation">.</span>SUCCESS<span class="token punctuation">;</span>
                            <span class="token punctuation">&#125;</span>

                            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">ConsumeMessageOrderlyService</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>defaultMQPushConsumerImpl<span class="token punctuation">.</span><span class="token function">hasHook</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                consumeMessageContext<span class="token punctuation">.</span><span class="token function">getProps</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span><span class="token class-name">MixAll</span><span class="token punctuation">.</span>CONSUME_CONTEXT_TYPE<span class="token punctuation">,</span> returnType<span class="token punctuation">.</span><span class="token function">name</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token punctuation">&#125;</span>

                            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">null</span> <span class="token operator">==</span> status<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                status <span class="token operator">=</span> <span class="token class-name">ConsumeOrderlyStatus</span><span class="token punctuation">.</span>SUSPEND_CURRENT_QUEUE_A_MOMENT<span class="token punctuation">;</span>
                            <span class="token punctuation">&#125;</span>

                            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">ConsumeMessageOrderlyService</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>defaultMQPushConsumerImpl<span class="token punctuation">.</span><span class="token function">hasHook</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                consumeMessageContext<span class="token punctuation">.</span><span class="token function">setStatus</span><span class="token punctuation">(</span>status<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                                consumeMessageContext
                                    <span class="token punctuation">.</span><span class="token function">setSuccess</span><span class="token punctuation">(</span><span class="token class-name">ConsumeOrderlyStatus</span><span class="token punctuation">.</span>SUCCESS <span class="token operator">==</span> status <span class="token operator">||</span> <span class="token class-name">ConsumeOrderlyStatus</span><span class="token punctuation">.</span>COMMIT <span class="token operator">==</span> status<span class="token punctuation">)</span><span class="token punctuation">;</span>
                                <span class="token class-name">ConsumeMessageOrderlyService</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>defaultMQPushConsumerImpl<span class="token punctuation">.</span><span class="token function">executeHookAfter</span><span class="token punctuation">(</span>consumeMessageContext<span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token punctuation">&#125;</span>

                            <span class="token class-name">ConsumeMessageOrderlyService</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getConsumerStatsManager</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
                                <span class="token punctuation">.</span><span class="token function">incConsumeRT</span><span class="token punctuation">(</span><span class="token class-name">ConsumeMessageOrderlyService</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>consumerGroup<span class="token punctuation">,</span> messageQueue<span class="token punctuation">.</span><span class="token function">getTopic</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> consumeRT<span class="token punctuation">)</span><span class="token punctuation">;</span>

                            continueConsume <span class="token operator">=</span> <span class="token class-name">ConsumeMessageOrderlyService</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">processConsumeResult</span><span class="token punctuation">(</span>msgs<span class="token punctuation">,</span> status<span class="token punctuation">,</span> context<span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                            continueConsume <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
                        <span class="token punctuation">&#125;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>processQueue<span class="token punctuation">.</span><span class="token function">isDropped</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token string">"the message queue not be able to consume, because it's dropped. &#123;&#125;"</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>messageQueue<span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token keyword">return</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>

                    <span class="token class-name">ConsumeMessageOrderlyService</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">tryLockLaterAndReconsume</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>messageQueue<span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>processQueue<span class="token punctuation">,</span> <span class="token number">100</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>获取到锁对象后，使用synchronized尝试申请线程级独占锁。</p>
<p><strong>如果加锁成功</strong>，同一时刻只有一个线程进行消息消费。</p>
<p><strong>如果加锁失败</strong>，会延迟100ms重新尝试向broker端申请锁定messageQueue，锁定成功后重新提交消费请求</p>
<p>创建消息拉取任务时，消息客户端向broker端申请锁定MessageQueue，使得一个MessageQueue同一个时刻只能被一个消费客户端消费。</p>
<p>消息消费时，多线程针对同一个消息队列的消费先尝试使用synchronized申请独占锁，加锁成功才能进行消费，使得一个MessageQueue同一个时刻只能被一个消费客户端中一个线程消费。<br>这里其实还有很重要的一点是对processQueue的加锁，这里其实是保证了在 rebalance的过程中如果 processQueue 被分配给了另一个 consumer，但是当前已经被我这个 consumer 再消费，但是没提交，就有可能出现被两个消费者消费，所以得进行加锁保证不受 rebalance 影响。</p>
]]></content>
      <categories>
        <category>MQ</category>
        <category>RocketMQ</category>
        <category>消息队列</category>
      </categories>
      <tags>
        <tag>MQ</tag>
        <tag>消息队列</tag>
        <tag>RocketMQ</tag>
      </tags>
  </entry>
  <entry>
    <title>聊一下 SpringBoot 中使用的 cglib 作为动态代理中的一个注意点</title>
    <url>/2021/09/19/%E8%81%8A%E4%B8%80%E4%B8%8B-SpringBoot-%E4%B8%AD%E4%BD%BF%E7%94%A8%E7%9A%84-cglib-%E4%BD%9C%E4%B8%BA%E5%8A%A8%E6%80%81%E4%BB%A3%E7%90%86%E4%B8%AD%E7%9A%84%E4%B8%80%E4%B8%AA%E6%B3%A8%E6%84%8F%E7%82%B9/</url>
    <content><![CDATA[<p>这个话题是由一次组内同学分享引出来的，首先在 springboot 2.x 开始默认使用了 cglib 作为 aop 的实现，这里也稍微讲一下，在一个 1.x 的老项目里，可以看到AopAutoConfiguration 是这样的</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Configuration</span>
<span class="token annotation punctuation">@ConditionalOnClass</span><span class="token punctuation">(</span><span class="token punctuation">&#123;</span> <span class="token class-name">EnableAspectJAutoProxy</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">,</span> <span class="token class-name">Aspect</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">,</span> <span class="token class-name">Advice</span><span class="token punctuation">.</span><span class="token keyword">class</span> <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
<span class="token annotation punctuation">@ConditionalOnProperty</span><span class="token punctuation">(</span>prefix <span class="token operator">=</span> <span class="token string">"spring.aop"</span><span class="token punctuation">,</span> name <span class="token operator">=</span> <span class="token string">"auto"</span><span class="token punctuation">,</span> havingValue <span class="token operator">=</span> <span class="token string">"true"</span><span class="token punctuation">,</span> matchIfMissing <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">AopAutoConfiguration</span> <span class="token punctuation">&#123;</span>

	<span class="token annotation punctuation">@Configuration</span>
	<span class="token annotation punctuation">@EnableAspectJAutoProxy</span><span class="token punctuation">(</span>proxyTargetClass <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">)</span>
	<span class="token annotation punctuation">@ConditionalOnProperty</span><span class="token punctuation">(</span>prefix <span class="token operator">=</span> <span class="token string">"spring.aop"</span><span class="token punctuation">,</span> name <span class="token operator">=</span> <span class="token string">"proxy-target-class"</span><span class="token punctuation">,</span> havingValue <span class="token operator">=</span> <span class="token string">"false"</span><span class="token punctuation">,</span> matchIfMissing <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">)</span>
	<span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">class</span> <span class="token class-name">JdkDynamicAutoProxyConfiguration</span> <span class="token punctuation">&#123;</span>
	<span class="token punctuation">&#125;</span>

	<span class="token annotation punctuation">@Configuration</span>
	<span class="token annotation punctuation">@EnableAspectJAutoProxy</span><span class="token punctuation">(</span>proxyTargetClass <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">)</span>
	<span class="token annotation punctuation">@ConditionalOnProperty</span><span class="token punctuation">(</span>prefix <span class="token operator">=</span> <span class="token string">"spring.aop"</span><span class="token punctuation">,</span> name <span class="token operator">=</span> <span class="token string">"proxy-target-class"</span><span class="token punctuation">,</span> havingValue <span class="token operator">=</span> <span class="token string">"true"</span><span class="token punctuation">,</span> matchIfMissing <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">)</span>
	<span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">class</span> <span class="token class-name">CglibAutoProxyConfiguration</span> <span class="token punctuation">&#123;</span>
	<span class="token punctuation">&#125;</span>

<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>而在 2.x 中变成了这样</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Configuration</span><span class="token punctuation">(</span>proxyBeanMethods <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">)</span>
<span class="token annotation punctuation">@ConditionalOnProperty</span><span class="token punctuation">(</span>prefix <span class="token operator">=</span> <span class="token string">"spring.aop"</span><span class="token punctuation">,</span> name <span class="token operator">=</span> <span class="token string">"auto"</span><span class="token punctuation">,</span> havingValue <span class="token operator">=</span> <span class="token string">"true"</span><span class="token punctuation">,</span> matchIfMissing <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">AopAutoConfiguration</span> <span class="token punctuation">&#123;</span>

	<span class="token annotation punctuation">@Configuration</span><span class="token punctuation">(</span>proxyBeanMethods <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">)</span>
	<span class="token annotation punctuation">@ConditionalOnClass</span><span class="token punctuation">(</span><span class="token class-name">Advice</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span>
	<span class="token keyword">static</span> <span class="token keyword">class</span> <span class="token class-name">AspectJAutoProxyingConfiguration</span> <span class="token punctuation">&#123;</span>

		<span class="token annotation punctuation">@Configuration</span><span class="token punctuation">(</span>proxyBeanMethods <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">)</span>
		<span class="token annotation punctuation">@EnableAspectJAutoProxy</span><span class="token punctuation">(</span>proxyTargetClass <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">)</span>
		<span class="token annotation punctuation">@ConditionalOnProperty</span><span class="token punctuation">(</span>prefix <span class="token operator">=</span> <span class="token string">"spring.aop"</span><span class="token punctuation">,</span> name <span class="token operator">=</span> <span class="token string">"proxy-target-class"</span><span class="token punctuation">,</span> havingValue <span class="token operator">=</span> <span class="token string">"false"</span><span class="token punctuation">)</span>
		<span class="token keyword">static</span> <span class="token keyword">class</span> <span class="token class-name">JdkDynamicAutoProxyConfiguration</span> <span class="token punctuation">&#123;</span>

		<span class="token punctuation">&#125;</span>

		<span class="token annotation punctuation">@Configuration</span><span class="token punctuation">(</span>proxyBeanMethods <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">)</span>
		<span class="token annotation punctuation">@EnableAspectJAutoProxy</span><span class="token punctuation">(</span>proxyTargetClass <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">)</span>
		<span class="token annotation punctuation">@ConditionalOnProperty</span><span class="token punctuation">(</span>prefix <span class="token operator">=</span> <span class="token string">"spring.aop"</span><span class="token punctuation">,</span> name <span class="token operator">=</span> <span class="token string">"proxy-target-class"</span><span class="token punctuation">,</span> havingValue <span class="token operator">=</span> <span class="token string">"true"</span><span class="token punctuation">,</span>
				matchIfMissing <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">)</span>
		<span class="token keyword">static</span> <span class="token keyword">class</span> <span class="token class-name">CglibAutoProxyConfiguration</span> <span class="token punctuation">&#123;</span>

		<span class="token punctuation">&#125;</span>

	<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>为何会加载 AopAutoConfiguration 在前面的文章<a href="https://nicksxs.me/2021/07/11/%E8%81%8A%E8%81%8ASpringBoot-%E8%87%AA%E5%8A%A8%E8%A3%85%E9%85%8D/">聊聊 SpringBoot 自动装配</a>里已经介绍过，有兴趣的可以看下，可以发现 springboot 在 2.x 版本开始使用 cglib 作为默认的动态代理实现。</p>
<p>然后就是出现的问题了，代码是这样的，一个简单的基于 springboot 的带有数据库的插入，对插入代码加了事务注解，</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Mapper</span>
<span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">StudentMapper</span> <span class="token punctuation">&#123;</span>
		<span class="token comment">// 就是插入一条数据</span>
    <span class="token annotation punctuation">@Insert</span><span class="token punctuation">(</span><span class="token string">"insert into student(name, age)"</span> <span class="token operator">+</span> <span class="token string">"values ('nick', '18')"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token class-name">Long</span> <span class="token function">insert</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>

<span class="token annotation punctuation">@Component</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">StudentManager</span> <span class="token punctuation">&#123;</span>

    <span class="token annotation punctuation">@Resource</span>
    <span class="token keyword">private</span> <span class="token class-name">StudentMapper</span> studentMapper<span class="token punctuation">;</span>
    
    <span class="token keyword">public</span> <span class="token class-name">Long</span> <span class="token function">createStudent</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> studentMapper<span class="token punctuation">.</span><span class="token function">insert</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>

<span class="token annotation punctuation">@Component</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">StudentServiceImpl</span> <span class="token keyword">implements</span> <span class="token class-name">StudentService</span> <span class="token punctuation">&#123;</span>

    <span class="token annotation punctuation">@Resource</span>
    <span class="token keyword">private</span> <span class="token class-name">StudentManager</span> studentManager<span class="token punctuation">;</span>

    <span class="token comment">// 自己引用</span>
    <span class="token annotation punctuation">@Resource</span>
    <span class="token keyword">private</span> <span class="token class-name">StudentServiceImpl</span> studentService<span class="token punctuation">;</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token annotation punctuation">@Transactional</span>
    <span class="token keyword">public</span> <span class="token class-name">Long</span> <span class="token function">createStudent</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">Long</span> id <span class="token operator">=</span> studentManager<span class="token punctuation">.</span><span class="token function">createStudent</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Long</span> id2 <span class="token operator">=</span> studentService<span class="token punctuation">.</span><span class="token function">createStudent2</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> <span class="token number">1L</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token annotation punctuation">@Transactional</span>
    <span class="token keyword">private</span> <span class="token class-name">Long</span> <span class="token function">createStudent2</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
<span class="token comment">//        Integer t = Integer.valueOf("aaa");</span>
        <span class="token keyword">return</span> studentManager<span class="token punctuation">.</span><span class="token function">createStudent</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>第一个公有方法 createStudent 首先调用了 manager 层的创建方法，然后再通过引入的 studentService 调用了createStudent2，我们先跑一下看看会出现啥情况，果不其然报错了，正是这个报错让我纠结了很久</p>
<p><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/EdR7oB.png" alt="EdR7oB"></p>
<p>报了个空指针，而且是在 createStudent2 已经被调用到了，在它的内部，报的 studentManager 是 null，首先 cglib 作为动态代理它是通过继承的方式来实现的，相当于是会在调用目标对象的代理方法时调用 cglib 生成的子类，具体的代理切面逻辑在子类实现，然后在调用目标对象的目标方法，但是继承的方式对于 final 和私有方法其实是没法进行代理的，因为没法继承，所以我最开始的想法是应该通过 studentService 调用 createStudent2 的时候就报错了，也就是不会进入这个方法内部，后面才发现犯了个特别二的错误，继承的方式去调用父类的私有方法，对于 Java 来说是可以调用到的，父类的私有方法并不由子类的InstanceKlass维护，只能通过子类的InstanceKlass找到Java类对应的_super，这样间接地访问。也就是说子类其实是可以访问的，那为啥访问了会报空指针呢，这里报的是studentManager 是空的，可以往依赖注入方面去想，如果忽略依赖注入，我这个studentManager 的确是 null，那是不是就没有被依赖注入呢，但是为啥前面那个可以呢</p>
<p>这个问题着实查了很久，不废话来看代码</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Override</span>
		<span class="token keyword">protected</span> <span class="token class-name">Object</span> <span class="token function">invokeJoinpoint</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">Throwable</span> <span class="token punctuation">&#123;</span>
			<span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>methodProxy <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">// 这里的 target 就是被代理的 bean</span>
				<span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span>methodProxy<span class="token punctuation">.</span><span class="token function">invoke</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>target<span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>arguments<span class="token punctuation">)</span><span class="token punctuation">;</span>
			<span class="token punctuation">&#125;</span>
			<span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
				<span class="token keyword">return</span> <span class="token keyword">super</span><span class="token punctuation">.</span><span class="token function">invokeJoinpoint</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
			<span class="token punctuation">&#125;</span>
		<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<p>这个是<code>org.springframework.aop.framework.CglibAopProxy.CglibMethodInvocation</code>的代码，其实它在这里不是直接调用 super 也就是父类的方法，而是通过 methodProxy 调用 target 目标对象的方法，也就是原始的 studentService bean 的方法，这样子 spring 管理的已经做好依赖注入的 bean 就能正常起作用，否则就会出现上面的问题，因为 cglib 其实是通过继承来实现，通过将调用转移到子类上加入代理逻辑，我们在简单使用的时候会直接 invokeSuper() 调用父类的方法，但是在这里 spring 的场景里需要去支持 spring 的功能逻辑，所以上面的问题就可以开始来解释了，因为 createStudent 是公共方法，cglib 可以对其进行继承代理，但是在执行逻辑的时候其实是通过调用目标对象，也就是 spring 管理的被代理的目标对象的 bean 调用的 createStudent，而对于下面的 createStudent2 方法因为是私有方法，不会走代理逻辑，也就不会有调用回目标对象的逻辑，只是通过继承关系，在子类中没有这个方法，所以会通过子类的InstanceKlass找到这个类对应的_super，然后调用父类的这个私有方法，这里要搞清楚一个点，从这个代理类直接找到其父类然后调用这个私有方法，这个类是由 cglib 生成的，不是被 spring 管理起来经过依赖注入的 bean，所以是没有 studentManager 这个依赖的，也就出现了前面的问题</p>
<p>而在前面提到的cglib通过methodProxy调用到目标对象，目标对象是在什么时候设置的呢，其实是在bean的生命周期中，org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization这个接口的在bean的初始化过程中，会调用实现了这个接口的方法，</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Override</span>
<span class="token keyword">public</span> <span class="token class-name">Object</span> <span class="token function">postProcessAfterInitialization</span><span class="token punctuation">(</span><span class="token annotation punctuation">@Nullable</span> <span class="token class-name">Object</span> bean<span class="token punctuation">,</span> <span class="token class-name">String</span> beanName<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">if</span> <span class="token punctuation">(</span>bean <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
		<span class="token class-name">Object</span> cacheKey <span class="token operator">=</span> <span class="token function">getCacheKey</span><span class="token punctuation">(</span>bean<span class="token punctuation">.</span><span class="token function">getClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> beanName<span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>earlyProxyReferences<span class="token punctuation">.</span><span class="token function">remove</span><span class="token punctuation">(</span>cacheKey<span class="token punctuation">)</span> <span class="token operator">!=</span> bean<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
			<span class="token keyword">return</span> <span class="token function">wrapIfNecessary</span><span class="token punctuation">(</span>bean<span class="token punctuation">,</span> beanName<span class="token punctuation">,</span> cacheKey<span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token punctuation">&#125;</span>
	<span class="token punctuation">&#125;</span>
	<span class="token keyword">return</span> bean<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>具体的逻辑在 org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#wrapIfNecessary这个方法里</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">protected</span> <span class="token class-name">Object</span> <span class="token function">getCacheKey</span><span class="token punctuation">(</span><span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span> beanClass<span class="token punctuation">,</span> <span class="token annotation punctuation">@Nullable</span> <span class="token class-name">String</span> beanName<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
		<span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">StringUtils</span><span class="token punctuation">.</span><span class="token function">hasLength</span><span class="token punctuation">(</span>beanName<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
			<span class="token keyword">return</span> <span class="token punctuation">(</span><span class="token class-name">FactoryBean</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">.</span><span class="token function">isAssignableFrom</span><span class="token punctuation">(</span>beanClass<span class="token punctuation">)</span> <span class="token operator">?</span>
					<span class="token class-name">BeanFactory</span><span class="token punctuation">.</span>FACTORY_BEAN_PREFIX <span class="token operator">+</span> beanName <span class="token operator">:</span> beanName<span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token punctuation">&#125;</span>
		<span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
			<span class="token keyword">return</span> beanClass<span class="token punctuation">;</span>
		<span class="token punctuation">&#125;</span>
	<span class="token punctuation">&#125;</span>

	<span class="token comment">/**
	 * Wrap the given bean if necessary, i.e. if it is eligible for being proxied.
	 * @param bean the raw bean instance
	 * @param beanName the name of the bean
	 * @param cacheKey the cache key for metadata access
	 * @return a proxy wrapping the bean, or the raw bean instance as-is
	 */</span>
	<span class="token keyword">protected</span> <span class="token class-name">Object</span> <span class="token function">wrapIfNecessary</span><span class="token punctuation">(</span><span class="token class-name">Object</span> bean<span class="token punctuation">,</span> <span class="token class-name">String</span> beanName<span class="token punctuation">,</span> <span class="token class-name">Object</span> cacheKey<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
		<span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">StringUtils</span><span class="token punctuation">.</span><span class="token function">hasLength</span><span class="token punctuation">(</span>beanName<span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> <span class="token keyword">this</span><span class="token punctuation">.</span>targetSourcedBeans<span class="token punctuation">.</span><span class="token function">contains</span><span class="token punctuation">(</span>beanName<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
			<span class="token keyword">return</span> bean<span class="token punctuation">;</span>
		<span class="token punctuation">&#125;</span>
		<span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">Boolean</span><span class="token punctuation">.</span>FALSE<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>advisedBeans<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span>cacheKey<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
			<span class="token keyword">return</span> bean<span class="token punctuation">;</span>
		<span class="token punctuation">&#125;</span>
		<span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">isInfrastructureClass</span><span class="token punctuation">(</span>bean<span class="token punctuation">.</span><span class="token function">getClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token operator">||</span> <span class="token function">shouldSkip</span><span class="token punctuation">(</span>bean<span class="token punctuation">.</span><span class="token function">getClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> beanName<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
			<span class="token keyword">this</span><span class="token punctuation">.</span>advisedBeans<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span>cacheKey<span class="token punctuation">,</span> <span class="token class-name">Boolean</span><span class="token punctuation">.</span>FALSE<span class="token punctuation">)</span><span class="token punctuation">;</span>
			<span class="token keyword">return</span> bean<span class="token punctuation">;</span>
		<span class="token punctuation">&#125;</span>

		<span class="token comment">// Create proxy if we have advice.</span>
		<span class="token class-name">Object</span><span class="token punctuation">[</span><span class="token punctuation">]</span> specificInterceptors <span class="token operator">=</span> <span class="token function">getAdvicesAndAdvisorsForBean</span><span class="token punctuation">(</span>bean<span class="token punctuation">.</span><span class="token function">getClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> beanName<span class="token punctuation">,</span> <span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token keyword">if</span> <span class="token punctuation">(</span>specificInterceptors <span class="token operator">!=</span> DO_NOT_PROXY<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
			<span class="token keyword">this</span><span class="token punctuation">.</span>advisedBeans<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span>cacheKey<span class="token punctuation">,</span> <span class="token class-name">Boolean</span><span class="token punctuation">.</span>TRUE<span class="token punctuation">)</span><span class="token punctuation">;</span>
			<span class="token class-name">Object</span> proxy <span class="token operator">=</span> <span class="token function">createProxy</span><span class="token punctuation">(</span>
					bean<span class="token punctuation">.</span><span class="token function">getClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> beanName<span class="token punctuation">,</span> specificInterceptors<span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">SingletonTargetSource</span><span class="token punctuation">(</span>bean<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
			<span class="token keyword">this</span><span class="token punctuation">.</span>proxyTypes<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span>cacheKey<span class="token punctuation">,</span> proxy<span class="token punctuation">.</span><span class="token function">getClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
			<span class="token keyword">return</span> proxy<span class="token punctuation">;</span>
		<span class="token punctuation">&#125;</span>

		<span class="token keyword">this</span><span class="token punctuation">.</span>advisedBeans<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span>cacheKey<span class="token punctuation">,</span> <span class="token class-name">Boolean</span><span class="token punctuation">.</span>FALSE<span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token keyword">return</span> bean<span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>然后在 <code>org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#createProxy</code> 中创建了代理类</p>
]]></content>
      <categories>
        <category>Java</category>
        <category>SpringBoot</category>
      </categories>
      <tags>
        <tag>Java</tag>
        <tag>SpringBoot</tag>
        <tag>Spring</tag>
        <tag>cglib</tag>
        <tag>事务</tag>
      </tags>
  </entry>
  <entry>
    <title>聊一下 SpringBoot 中动态切换数据源的方法</title>
    <url>/2021/09/26/%E8%81%8A%E4%B8%80%E4%B8%8B-SpringBoot-%E4%B8%AD%E5%8A%A8%E6%80%81%E5%88%87%E6%8D%A2%E6%95%B0%E6%8D%AE%E6%BA%90%E7%9A%84%E6%96%B9%E6%B3%95/</url>
    <content><![CDATA[<p>其实这个表示有点不太对，应该是 Druid 动态切换数据源的方法，只是应用在了 springboot 框架中，准备代码准备了半天，之前在一次数据库迁移中使用了，发现 Druid 还是很强大的，用来做动态数据源切换很方便。</p>
<p>首先这里的场景跟我原来用的有点点区别，在项目中使用的是通过配置中心控制数据源切换，统一切换，而这里的例子多加了个可以根据接口注解配置</p>
<p>第一部分是最核心的，如何基于 Spring JDBC 和 Druid 来实现数据源切换，是继承了<code>org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource</code> 这个类，他的<code>determineCurrentLookupKey</code>方法会被调用来获得用来决定选择那个数据源的对象，也就是 lookupKey，也可以通过这个类看到就是通过这个 lookupKey 来路由找到数据源。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">DynamicDataSource</span> <span class="token keyword">extends</span> <span class="token class-name">AbstractRoutingDataSource</span> <span class="token punctuation">&#123;</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">protected</span> <span class="token class-name">Object</span> <span class="token function">determineCurrentLookupKey</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">DatabaseContextHolder</span><span class="token punctuation">.</span><span class="token function">getDatabaseType</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> <span class="token class-name">DatabaseContextHolder</span><span class="token punctuation">.</span><span class="token function">getDatabaseType</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">return</span> <span class="token class-name">DatabaseType</span><span class="token punctuation">.</span>MASTER1<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>而如何使用这个 lookupKey 呢，就涉及到我们的 DataSource 配置了，原来就是我们可以直接通过spring 的 jdbc 配置数据源，像这样</p>
<p><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/VQPrT3.png"></p>
<p>现在我们要使用 Druid 作为数据源了，然后配置 <code>DynamicDataSource </code>的参数，通过 key 来选择对应的 DataSource，也就是下面配的 master1 和 master2</p>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>bean</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>master1<span class="token punctuation">"</span></span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.alibaba.druid.pool.DruidDataSource<span class="token punctuation">"</span></span> <span class="token attr-name">init-method</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>init<span class="token punctuation">"</span></span>
          <span class="token attr-name">destroy-method</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>close<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>driverClassName</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.mysql.cj.jdbc.Driver<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>url</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>$&#123;master1.demo.datasource.url&#125;<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>username</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>$&#123;master1.demo.datasource.username&#125;<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>password</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>$&#123;master1.demo.datasource.password&#125;<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>initialSize</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>5<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>minIdle</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>1<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>maxActive</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>10<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>maxWait</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>60000<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>timeBetweenEvictionRunsMillis</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>60000<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>minEvictableIdleTimeMillis</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>300000<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>validationQuery</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>SELECT <span class="token punctuation">'</span>x<span class="token punctuation">'</span><span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>testWhileIdle</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>true<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>testOnBorrow</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>false<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>testOnReturn</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>false<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>poolPreparedStatements</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>false<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>maxPoolPreparedStatementPerConnectionSize</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>20<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>connectionProperties</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>config.decrypt=true<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>filters</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>stat,config<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>

    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>bean</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>master2<span class="token punctuation">"</span></span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.alibaba.druid.pool.DruidDataSource<span class="token punctuation">"</span></span> <span class="token attr-name">init-method</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>init<span class="token punctuation">"</span></span>
          <span class="token attr-name">destroy-method</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>close<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>driverClassName</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.mysql.cj.jdbc.Driver<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>url</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>$&#123;master2.demo.datasource.url&#125;<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>username</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>$&#123;master2.demo.datasource.username&#125;<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>password</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>$&#123;master2.demo.datasource.password&#125;<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>initialSize</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>5<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>minIdle</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>1<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>maxActive</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>10<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>maxWait</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>60000<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>timeBetweenEvictionRunsMillis</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>60000<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>minEvictableIdleTimeMillis</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>300000<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>validationQuery</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>SELECT <span class="token punctuation">'</span>x<span class="token punctuation">'</span><span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>testWhileIdle</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>true<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>testOnBorrow</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>false<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>testOnReturn</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>false<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>poolPreparedStatements</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>false<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>maxPoolPreparedStatementPerConnectionSize</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>20<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>connectionProperties</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>config.decrypt=true<span class="token punctuation">"</span></span>
          <span class="token attr-name"><span class="token namespace">p:</span>filters</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>stat,config<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>

    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>bean</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>dataSource<span class="token punctuation">"</span></span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.nicksxs.springdemo.config.DynamicDataSource<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>property</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>targetDataSources<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>map</span> <span class="token attr-name">key-type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>java.lang.String<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
                <span class="token comment">&lt;!-- master --></span>
                <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>entry</span> <span class="token attr-name">key</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>master1<span class="token punctuation">"</span></span> <span class="token attr-name">value-ref</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>master1<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
                <span class="token comment">&lt;!-- slave --></span>
                <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>entry</span> <span class="token attr-name">key</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>master2<span class="token punctuation">"</span></span> <span class="token attr-name">value-ref</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>master2<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>map</span><span class="token punctuation">></span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>property</span><span class="token punctuation">></span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>property</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>defaultTargetDataSource<span class="token punctuation">"</span></span> <span class="token attr-name">ref</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>master1<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>bean</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>现在就要回到头上，介绍下这个<code>DatabaseContextHolder</code>，这里使用了 ThreadLocal 存放这个 DatabaseType，为啥要用这个是因为前面说的我们想要让接口层面去配置不同的数据源，要把持相互隔离不受影响，就使用了 ThreadLocal，关于它也可以看我前面写的一篇文章<a href="https://nicksxs.me/2021/05/30/%E8%81%8A%E8%81%8A%E4%BC%A0%E8%AF%B4%E4%B8%AD%E7%9A%84-ThreadLocal/">聊聊传说中的 ThreadLocal</a>，而 DatabaseType 就是个简单的枚举</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">DatabaseContextHolder</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">final</span> <span class="token class-name">ThreadLocal</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">DatabaseType</span><span class="token punctuation">></span></span> databaseTypeThreadLocal <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ThreadLocal</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token class-name">DatabaseType</span> <span class="token function">getDatabaseType</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> databaseTypeThreadLocal<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">putDatabaseType</span><span class="token punctuation">(</span><span class="token class-name">DatabaseType</span> databaseType<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        databaseTypeThreadLocal<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span>databaseType<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">clearDatabaseType</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        databaseTypeThreadLocal<span class="token punctuation">.</span><span class="token function">remove</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">public</span> <span class="token keyword">enum</span> <span class="token class-name">DatabaseType</span> <span class="token punctuation">&#123;</span>
    <span class="token function">MASTER1</span><span class="token punctuation">(</span><span class="token string">"master1"</span><span class="token punctuation">,</span> <span class="token string">"1"</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
    <span class="token function">MASTER2</span><span class="token punctuation">(</span><span class="token string">"master2"</span><span class="token punctuation">,</span> <span class="token string">"2"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token class-name">String</span> name<span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token class-name">String</span> value<span class="token punctuation">;</span>

    <span class="token class-name">DatabaseType</span><span class="token punctuation">(</span><span class="token class-name">String</span> name<span class="token punctuation">,</span> <span class="token class-name">String</span> value<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>name <span class="token operator">=</span> name<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>value <span class="token operator">=</span> value<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> name<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">getValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> value<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token class-name">DatabaseType</span> <span class="token function">getDatabaseType</span><span class="token punctuation">(</span><span class="token class-name">String</span> name<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>MASTER2<span class="token punctuation">.</span>name<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> MASTER2<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">return</span> MASTER1<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>这边可以看到就是通过动态地通过<code>putDatabaseType</code>设置<code>lookupKey</code>来进行数据源切换，要通过接口注解配置来进行设置的话，我们就需要一个注解</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Retention</span><span class="token punctuation">(</span><span class="token class-name">RetentionPolicy</span><span class="token punctuation">.</span>RUNTIME<span class="token punctuation">)</span>
<span class="token annotation punctuation">@Target</span><span class="token punctuation">(</span><span class="token class-name">ElementType</span><span class="token punctuation">.</span>METHOD<span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token annotation punctuation">@interface</span> <span class="token class-name">DataSource</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">String</span> <span class="token function">value</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>这个注解可以配置在我的接口方法上，比如这样</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">StudentService</span> <span class="token punctuation">&#123;</span>

    <span class="token annotation punctuation">@DataSource</span><span class="token punctuation">(</span><span class="token string">"master1"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token class-name">Student</span> <span class="token function">queryOne</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token annotation punctuation">@DataSource</span><span class="token punctuation">(</span><span class="token string">"master2"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token class-name">Student</span> <span class="token function">queryAnother</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>通过切面来进行数据源的设置</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Aspect</span>
<span class="token annotation punctuation">@Component</span>
<span class="token annotation punctuation">@Order</span><span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">DataSourceAspect</span> <span class="token punctuation">&#123;</span>

    <span class="token annotation punctuation">@Pointcut</span><span class="token punctuation">(</span><span class="token string">"execution(* com.nicksxs.springdemo.service..*.*(..))"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">pointCut</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>

    <span class="token punctuation">&#125;</span>


    <span class="token annotation punctuation">@Before</span><span class="token punctuation">(</span><span class="token string">"pointCut()"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">before</span><span class="token punctuation">(</span><span class="token class-name">JoinPoint</span> point<span class="token punctuation">)</span>
    <span class="token punctuation">&#123;</span>
        <span class="token class-name">Object</span> target <span class="token operator">=</span> point<span class="token punctuation">.</span><span class="token function">getTarget</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>target<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">String</span> method <span class="token operator">=</span> point<span class="token punctuation">.</span><span class="token function">getSignature</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>method<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span><span class="token punctuation">[</span><span class="token punctuation">]</span> classz <span class="token operator">=</span> target<span class="token punctuation">.</span><span class="token function">getClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getInterfaces</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span><span class="token punctuation">[</span><span class="token punctuation">]</span> parameterTypes <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token class-name">MethodSignature</span><span class="token punctuation">)</span> point<span class="token punctuation">.</span><span class="token function">getSignature</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">getMethod</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getParameterTypes</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">Method</span> m <span class="token operator">=</span> classz<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">.</span><span class="token function">getMethod</span><span class="token punctuation">(</span>method<span class="token punctuation">,</span> parameterTypes<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"method"</span><span class="token operator">+</span> m<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>m<span class="token punctuation">.</span><span class="token function">isAnnotationPresent</span><span class="token punctuation">(</span><span class="token class-name">DataSource</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token class-name">DataSource</span> data <span class="token operator">=</span> m<span class="token punctuation">.</span><span class="token function">getAnnotation</span><span class="token punctuation">(</span><span class="token class-name">DataSource</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"dataSource："</span><span class="token operator">+</span>data<span class="token punctuation">.</span><span class="token function">value</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token class-name">DatabaseContextHolder</span><span class="token punctuation">.</span><span class="token function">putDatabaseType</span><span class="token punctuation">(</span><span class="token class-name">DatabaseType</span><span class="token punctuation">.</span><span class="token function">getDatabaseType</span><span class="token punctuation">(</span>data<span class="token punctuation">.</span><span class="token function">value</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>

        <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token annotation punctuation">@After</span><span class="token punctuation">(</span><span class="token string">"pointCut()"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">after</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
				<span class="token class-name">DatabaseContextHolder</span><span class="token punctuation">.</span><span class="token function">clearDatabaseType</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>通过接口判断是否带有注解跟是注解的值，DatabaseType 的配置不太好，不过先忽略了，然后在切点后进行清理</p>
<p>这是我 master1 的数据，</p>
<p><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/sdQuJo.png"></p>
<p>master2 的数据</p>
<p><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/fXK1Wk.png"></p>
<p>然后跑一下简单的 demo，</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Override</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>args<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	LOGGER<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"run here"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>studentService<span class="token punctuation">.</span><span class="token function">queryOne</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>studentService<span class="token punctuation">.</span><span class="token function">queryAnother</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>看一下运行结果</p>
<p><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/42VAeq.png"></p>
<p>其实这个方法应用场景不止可以用来迁移数据库，还能实现精细化的读写数据源分离之类的，算是做个简单记录和分享。</p>
]]></content>
      <categories>
        <category>Java</category>
        <category>SpringBoot</category>
      </categories>
      <tags>
        <tag>Java</tag>
        <tag>SpringBoot</tag>
        <tag>Spring</tag>
        <tag>Druid</tag>
        <tag>数据源动态切换</tag>
      </tags>
  </entry>
  <entry>
    <title>聊在东京奥运会闭幕式这天-二</title>
    <url>/2021/08/19/%E8%81%8A%E5%9C%A8%E4%B8%9C%E4%BA%AC%E5%A5%A5%E8%BF%90%E4%BC%9A%E9%97%AD%E5%B9%95%E5%BC%8F%E8%BF%99%E5%A4%A9-%E4%BA%8C/</url>
    <content><![CDATA[<p>前面主要还是说了乒乓球的，因为整体还是乒乓球的比赛赛程比较长，比较激烈，扣人心弦，记得那会在公司没法看视频直播，就偶尔看看奥运会官网的比分，还几场马龙樊振东，陈梦被赢了一局就吓尿了，已经被混双那场留下了阴影，其实后面去看看16 年的比赛什么的，中国队虽然拿了这么多冠军，但是自改成 11 分制以来，其实都没办法那么完全彻底地碾压，而且像张继科，樊振东，陈梦都多少有些慢热，现在看来是马龙比较全面，不过看过了马龙，刘国梁，许昕等的一些过往经历，都是起起伏伏，即使是张怡宁这样的大魔王，也经历过逢王楠不赢的阶段，心态无法调整好。</p>
<p>其实最开始是举重项目，侯志慧是女子 49 公斤级的冠军，这场比赛是全场都看，其实看中国队的举重比赛跟跳水有点像，每一轮都需要到最后才能等到中国队，跳水其实每轮都有，举重会按照自己报的试举重量进行排名，重量大的会在后面举，抓举和挺举各三次试举机会，有时候会看着比较焦虑，一直等不来，怕一上来就没试举成功，而且中国队一般试举重量就是很大的，容易一次试举不成功就马上下一次，连着举其实压力会非常大，说实话真的是外行看热闹，每次都是多懂一点点，这次由于实在是比较无聊，所以看的会比较专心点，对于对应的规则知识点也会多了解一点，同时对于举重，没想到我们国家的这些运动员有这么强，最后八块金牌拿了七块，有一块拿到银牌也是有点因为教练的策略问题，这里其实也稍微知道一点，因为报上去的试举重量是谁小谁先举，并且我们国家都是实力非常强的，所以都会报大一些，并且如果这个项目有实力相近的选手，会比竞对多报一公斤，这样子如果前面竞争对手没举成功，我们把握就很大了，最坏的情况即使对手试举成功了，我们还有机会搏一把，比如谌利军这样的，只是说说感想，举重运动员真的是个比较单纯的群体，而且训练是非常痛苦枯燥的，非常容易受伤，像挺举就有点会压迫呼吸通道，看到好几个都是脸憋得通红，甚至直接因为压迫气道而没法完成后面的挺举，像之前 16 年的举重比赛，有个运动员没成功夺冠就非常愧疚地哭着说对不起祖国，没有获得冠军，这是怎么样的一种歉疚，怎么样的一种纯粹的感情呢，相对应地来说，我又要举男足，男篮的例子了，很多人在那嘲笑我这样对男足男篮愤愤不平的人，说可能我这样的人都没交个税（从缴纳个税的数量比例来算有可能），只是这里有两个打脸的事情，我足额缴纳个税，接近 20%的薪资都缴了个税，并且我买的所有东西都缴了增值税，如果让我这样缴纳了个税，缴纳了增值税的有个人的投票权，我一定会投票不让男足男篮使用我缴纳我的税金，用我们的缴纳的税，打出这么烂的表现，想乒乓球混双，拿个亚军都会被喷，那可是世界第二了，而且是就输了那么一场，足球篮球呢，我觉得是一方面成绩差，因为比赛真的有状态跟心态的影响，偶尔有一场失误非常正常，NBA 被黑八的有这么多强队，但是如果像男足男篮，成绩是越来越差，用范志毅的话来说就是脸都不要了，还有就是精气神，要在比赛中打出胜负欲，保持这种争胜心，才有机会再进步，前火箭队主教练鲁迪·汤姆贾诺维奇的话，“永远不要低估冠军的决心”，即使我现在打不过你，我会在下一次，下下次打败你，竞技体育永远要有这种精神，可以接受一时的失败，但是要保持永远争胜的心。</p>
<p>第一块金牌是杨倩拿下的，中国队拿奥运会首金也是有政治任务的，而恰恰杨倩这个金牌也有点碰巧是对手最后一枪失误了，当然竞技体育，特别是射击，真的是容不得一点点失误，像前面几届的美国神通埃蒙斯，失之毫厘差之千里，但是这个具体评价就比较少，唯一一点让我比较出戏的就是杨倩真的非常像王刚的徒弟漆二娃，哈哈，微博上也有挺多人觉得像，射击还是个比较可以接受年纪稍大的运动员，需要经验和稳定性，相对来说爆发力体力稍好一点，像庞伟这样的，混合团体10米气手枪金牌，36 岁可能其他项目已经是年龄很大了，不过前面说的举重的吕小军军神也是年纪蛮大了，但是非常强，而且在油管上简直就是个神，相对来说射击是关注比较少，杨倩的也只是看了后面拿到冠军这个结果，有些因为时间或者电视上没放，但是成绩还是不错的，没多少喷点。</p>
<p>第二篇先到这，纯主观，轻喷。</p>
]]></content>
      <categories>
        <category>生活</category>
        <category>运动</category>
      </categories>
      <tags>
        <tag>生活</tag>
        <tag>运动</tag>
        <tag>东京奥运会</tag>
        <tag>举重</tag>
        <tag>射击</tag>
      </tags>
  </entry>
  <entry>
    <title>聊在东京奥运会闭幕式这天</title>
    <url>/2021/08/08/%E8%81%8A%E5%9C%A8%E4%B8%9C%E4%BA%AC%E5%A5%A5%E8%BF%90%E4%BC%9A%E9%97%AD%E5%B9%95%E5%BC%8F%E8%BF%99%E5%A4%A9/</url>
    <content><![CDATA[<p>这届奥运会有可能是我除了 08 年之外关注度最高的一届奥运会，原因可能是因为最近也没什么电影综艺啥的比较好看，前面看跑男倒还行，不是说多好，也就图一乐，最开始看向往的生活觉得也挺不错的，后面变成了统一来了就看黄磊做饭，然后夸黄磊做饭好吃，然后无聊的说这种生活多么多么美好，单调无聊，差不多弃了，这里面还包括大华不在了，大华其实个人还是有点呱噪的，但是挺能搞气氛，并且也有才华，彭彭跟子枫人是不讨厌，但是撑不起来，所以也导致了前面说的结果，都变成了黄磊彩虹屁现场，虽然偶尔怀疑他是否做得好吃，但是整体还是承认的，可对于一个这么多季了的综艺来说，这样也有点单调了。</p>
<p>还有奥运会像乒乓球，篮球，跳水这几个都是比较喜欢的项目，篮球🏀是从初中开始就也有在自己在玩的，虽然因为身高啊体质基本没什么天赋，但也算是热爱驱动，差不多到了大学因为比较懒才放下了，初中高中还是有很多时间花在上面，不像别人经常打球跑跑跳跳还能长高，我反而一直都没长个子，也因为这个其实蛮遗憾的，后面想想可能是初中的时候远走他乡去住宿读初中，伙食营养跟不上导致的，可能也是自己的一厢情愿吧，总觉得应该还能再长点个，这一点以后我自己的小孩我应该会特别注意这段时间他/她的营养摄入了；然后像乒乓球🏓的话其实小时候是比较讨厌的，因为家里人，父母都没有这类爱好习惯，我也完全不会，但是小学那会班里的“恶霸”就以公平之名要我们男生每个人都排队打几个，我这种不会的反而又要被嘲笑，这个小时候的阴影让我有了比较不好的印象，对它🏓的改观是在工作以后，前司跟一个同样不会的同事经常在饭点会打打，而且那会因为这个其实身体得到了锻炼，感觉是个不错的健身方式，然后又是中国的优势项目，小时候跟着我爸看孔令辉，那时候完全不懂，印象就觉得老瓦很牛，后面其实也没那么关注，上一届好像看了马龙的比赛；跳水也是中国的优势项目，而且也比较简单，不是说真的很简单，就是我们外行观众看着就看看水花大小图一乐。</p>
<p>这次的观赛过程其实主要还是在乒乓球上面，现在都有点怪我的乌鸦嘴，混双我一直就不太放心（关我什么事，我也不专业），然后一直觉得混双是不是不太稳，结果那天看的时候也是因为央视一套跟五套都没放，我家的有线电视又是没有五加体育，然后用电脑投屏就很卡，看得也很不爽，同时那天因为看的时候已经是 2:0还是再后面点了，一方面是不懂每队只有一次暂停，另一方面不知道已经用过暂停了，所以就特别怀疑马林是不是只会无脑鼓掌，感觉作为教练，并且是前冠军，应该也能在擦汗间隙，或者局间休息调整的时候多给些战略战术的指导，类似于后面男团小胖打奥恰洛夫，像解说都看出来了，其实奥恰那会的反手特别顺，打得特别凶，那就不能让他能特别顺手的上反手位，这当然是外行比较粗浅的看法，在混双过程中其实除了这个，还有让人很不爽的就是我们的许昕跟刘诗雯有种拿不出破釜沉舟的勇气的感觉，在气势上完全被对面两位日本乒乓球最讨厌的两位对手压制着，我都要输了，我就每一颗都要不让你好过，因为真的不是说没有实力，对面水谷隼也不是多么多么强的，可能上一届男团许昕输给他还留着阴影，但是以许昕 19 年男单世界第一的实力，目前也排在世界前三，输一场不应该成为这种阻力，有一些失误也很可惜，后面孙颖莎真的打得很解气，第二局一度以为又要被翻盘了，结果来了个大逆转，女团的时候也是，感觉在心态上孙颖莎还是很值得肯定的，少年老成这个词很适合，看其他的视频也觉得莎莎萌萌哒，陈梦总感觉还欠一点王者霸气，王曼昱还是可以的，反手很凶，我觉得其实这一届日本女乒就是打得非常凶，即使像平野这种看着很弱的妹子，打的球可一点都不弱，也是这种凶狠的打法，有点要压制中国的感觉，这方面我觉得是需要改善的，打这种要不就是实力上的完全碾压，要不就是我实力虽然比较没强多少，但是你狠我打得比你还狠，越保守越要输，我不太成熟的想法是这样的，还有就是面对逆境，这个就要说到男队的了，樊振东跟马龙在半决赛的时候，特别是男团的第二盘，樊振东打奥恰很好地表现了这个心态，当然樊振东我不是特别了解，据说他是比较善于打相持，比较善于焦灼的情况，不过整体看下来樊振东还是有一些欠缺，就是面对情况的快速转变应对，这一点也是马龙特别强的，虽然看起来马龙真的是年纪大了点，没有 16 年那会满头发胶，油光锃亮的大背头和满脸胶原蛋白的意气风发，大范围运动能力也弱了一点，但是经验和能力的全面性也让他最终能再次站上巅峰，还是非常佩服的，这里提一下张继科，虽然可能天赋上是张继科更强点，但是男乒一直都是有强者出现，能为国家队付出这么多并且一直坚持的可不是人人都可以，即使现在同台竞技马龙打不过张继科我还是更喜欢马龙。再来说说我们的对手，主要分三部分，德国男乒，里面有波尔（我刚听到的时候在想怎么又出来个叫波尔的，是不是像举重的石智勇一样，又来一个同名的，结果是同一个，已经四十岁了），这真是个让人敬佩的对手，实力强，经验丰富，虽然男单有点可惜，但是帮助男团获得银牌，真的是起到了定海神针的作用；奥恰洛夫，以前完全不认识，或者说看过也忘了，这次是真的有点意外，竟然有这么个马龙护法，其实他也坦言非常想赢一次马龙，并且在半决赛也非常接近赢得比赛，是个实力非常强的对手，就是男团半决赛输给张本智和有点可惜，有点被打蒙的感觉，佛朗西斯卡的话也是实力不错的选手，就是可能被奥恰跟波尔的光芒掩盖了，跟波尔在男团第一盘男双的比赛中打败日本那对男双也是非常给力的，说实话，最后打国乒的时候的确是国乒实力更胜一筹，但是即使德国赢了我也是充满尊敬，拼的就是硬实力，就像第二盘奥恰打樊振东，反手是真的很强，反过来看奥恰可能也不是很善于快速调整，樊振东打出来自己的节奏，主攻奥恰的中路，他好像没什么好办法解决。再来说我最讨厌的日本，嗯，小日本，张本智和、水谷隼、伊藤美诚，一一评价下（我是外行，绝对主观评价），张本智和，父母也是中国人，原来叫张智和，改日本籍后加了个本，被微博网友笑称日本尖叫鸡，男单输给了斯洛文尼亚选手，男团里是赢了两场，但是在我看来其实实力上可能比不上全力的奥恰，主要是特别能叫，会干扰对手，如果觉得这种也是种能力我也无话可说，要是有那种吼声能直接把对手震聋的，都不需要打比赛了，我简单记了下，赢一颗球，他要叫八声，用 LD 的话来说烦都烦死了，心态是在面对一些困境顺境的应对调整适应能力，而不是对这种噪音的适应能力，至少我是这么看的，所以我很期待樊振东能好好地虐虐他，因为其他像林昀儒真的是非常优秀的新选手，所谓的国乒克星估计也是小日本自己说说的，国乒其实有很多对手，马龙跟樊振东在男单半决赛碰到的这两个几乎都差点把他们掀翻了，所以还是练好自己的实力再来吹吧，免得打脸；水谷隼的话真的是长相就是特别地讨厌，还搞出那套不打比赛的姿态，男团里被波尔干掉就是很好的例子，波尔虽然真的很强，但毕竟 40 岁了，跟伊藤美诚一起说了吧，伊藤实力说实话是有的，混双中很大一部分的赢面来自于她，刘诗雯做了手术状态不好，许昕失误稍多，但是这种赢球了就感觉我赢了你一辈子一场没输的感觉，还有那种不知道怎么形容的笑，实力强的正常打比赛的我都佩服，像女团决赛里，平野跟石川佳纯的打法其实也很凶狠，但是都是正常的比赛，即使中国队两位实力不济输了也很正常，这种就真的需要像孙颖莎这样的小魔王无视各种魔法攻击，无视你各种花里胡哨的打法的人好好教训一下，混双输了以后了解了下她，感觉实力真的不错，是个大威胁，但是其实我们孙颖莎也是经历了九个月的继续成长，像张怡宁也评价了她，可能后面就没什么空间了，当然如果由张怡宁来打她就更适合了，净整这些有的没的，就打得你没脾气。</p>
<p>乒乓球的说的有点多，就分篇说了，第一篇先到这。</p>
]]></content>
      <categories>
        <category>生活</category>
        <category>运动</category>
      </categories>
      <tags>
        <tag>生活</tag>
        <tag>运动</tag>
        <tag>东京奥运会</tag>
        <tag>乒乓球</tag>
        <tag>跳水</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊 Dubbo 的 SPI 续之自适应拓展</title>
    <url>/2020/06/06/%E8%81%8A%E8%81%8A-Dubbo-%E7%9A%84-SPI-%E7%BB%AD%E4%B9%8B%E8%87%AA%E9%80%82%E5%BA%94%E6%8B%93%E5%B1%95/</url>
    <content><![CDATA[<h2 id="Adaptive"><a href="#Adaptive" class="headerlink" title="Adaptive"></a>Adaptive</h2><p>这个应该是 Dubbo SPI 里最玄妙的东西了，一开始没懂，自适应扩展点加载，<br><code>dubbo://123.123.123.123:1234/com.nicksxs.demo.service.HelloWorldService?anyhost=true&amp;application=demo&amp;default.loadbalance=random&amp;default.service.filter=LoggerFilter&amp;dubbo=2.5.3&amp;interface=com.nicksxs.demo.service.HelloWorldService&amp;logger=slf4j&amp;methods=method1,method2,method3,method4&amp;pid=4292&amp;retries=0&amp;side=provider&amp;threadpool=fixed&amp;threads=200&amp;timeout=2000&amp;timestamp=1590647155886</code><br>那我从比较能理解的角度或者说思路去讲讲我的理解，因为直接将原理如果脱离了使用，对于我这样的理解能力比较差的可能会比较吃力，从使用场景开始讲可能会比较舒服了，这里可以看到参数里有蛮多的，举个例子，比如这个 <code>threadpool = fixed</code>，说明线程池使用的是 fixed 对应的实现，也就是下图的这个<br><img data-src="https://mystore-1255223546.cos.ap-chengdu.myqcloud.com/uPic/4AAOaW.png"><br>这样子似乎没啥问题了，反正就是用dubbo 的 spi 加载嘛，好像没啥问题，其实问题还是存在的，或者说不太优雅，比如要先判断我这个 fixed 对应的实现类是哪个，这里可能就有个 if-else 判断了，但是 dubbo 的开发人员似乎不太想这么做这个事情，</p>
<p>譬如我们在引用一个服务时，在ReferenceConfig 中的</p>
<pre class="line-numbers language-Java" data-language="Java"><code class="language-Java">private static final Protocol refprotocol &#x3D; ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>就获取了自适应拓展，</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">T</span> <span class="token function">getAdaptiveExtension</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">Object</span> instance <span class="token operator">=</span> cachedAdaptiveInstance<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>instance <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>createAdaptiveInstanceError <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">synchronized</span> <span class="token punctuation">(</span>cachedAdaptiveInstance<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    instance <span class="token operator">=</span> cachedAdaptiveInstance<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">if</span> <span class="token punctuation">(</span>instance <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                            instance <span class="token operator">=</span> <span class="token function">createAdaptiveExtension</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                            cachedAdaptiveInstance<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span>instance<span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Throwable</span> t<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                            createAdaptiveInstanceError <span class="token operator">=</span> t<span class="token punctuation">;</span>
                            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">IllegalStateException</span><span class="token punctuation">(</span><span class="token string">"fail to create adaptive instance: "</span> <span class="token operator">+</span> t<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> t<span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token punctuation">&#125;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">IllegalStateException</span><span class="token punctuation">(</span><span class="token string">"fail to create adaptive instance: "</span> <span class="token operator">+</span> createAdaptiveInstanceError<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> createAdaptiveInstanceError<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">return</span> <span class="token punctuation">(</span><span class="token class-name">T</span><span class="token punctuation">)</span> instance<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>这里也使用了 DCL，来锁cachedAdaptiveInstance，当缓存中没有时就去创建自适应拓展</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">private</span> <span class="token class-name">T</span> <span class="token function">createAdaptiveExtension</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
          <span class="token comment">// 获取自适应拓展类然后实例化</span>
            <span class="token keyword">return</span> <span class="token function">injectExtension</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token class-name">T</span><span class="token punctuation">)</span> <span class="token function">getAdaptiveExtensionClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">newInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">IllegalStateException</span><span class="token punctuation">(</span><span class="token string">"Can not create adaptive extension "</span> <span class="token operator">+</span> type <span class="token operator">+</span> <span class="token string">", cause: "</span> <span class="token operator">+</span> e<span class="token punctuation">.</span><span class="token function">getMessage</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>

<span class="token keyword">private</span> <span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span> <span class="token function">getAdaptiveExtensionClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
  			<span class="token comment">// 这里会获取拓展类，如果没有自适应的拓展类，那么就需要调用createAdaptiveExtensionClass</span>
        <span class="token function">getExtensionClasses</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>cachedAdaptiveClass <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> cachedAdaptiveClass<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">return</span> cachedAdaptiveClass <span class="token operator">=</span> <span class="token function">createAdaptiveExtensionClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token keyword">private</span> <span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span> <span class="token function">createAdaptiveExtensionClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
  			<span class="token comment">// 这里去生成了自适应拓展的代码，具体生成逻辑比较复杂先不展开讲</span>
        <span class="token class-name">String</span> code <span class="token operator">=</span> <span class="token function">createAdaptiveExtensionClassCode</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">ClassLoader</span> classLoader <span class="token operator">=</span> <span class="token function">findClassLoader</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>alibaba<span class="token punctuation">.</span>dubbo<span class="token punctuation">.</span>common<span class="token punctuation">.</span>compiler<span class="token punctuation">.</span></span>Compiler</span> compiler <span class="token operator">=</span> <span class="token class-name">ExtensionLoader</span><span class="token punctuation">.</span><span class="token function">getExtensionLoader</span><span class="token punctuation">(</span><span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>alibaba<span class="token punctuation">.</span>dubbo<span class="token punctuation">.</span>common<span class="token punctuation">.</span>compiler<span class="token punctuation">.</span></span>Compiler</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getAdaptiveExtension</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> compiler<span class="token punctuation">.</span><span class="token function">compile</span><span class="token punctuation">(</span>code<span class="token punctuation">,</span> classLoader<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>生成的代码像这样</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">package</span> <span class="token namespace">com<span class="token punctuation">.</span>alibaba<span class="token punctuation">.</span>dubbo<span class="token punctuation">.</span>rpc</span><span class="token punctuation">;</span>

<span class="token keyword">import</span> <span class="token namespace">com<span class="token punctuation">.</span>alibaba<span class="token punctuation">.</span>dubbo<span class="token punctuation">.</span>common<span class="token punctuation">.</span>extension<span class="token punctuation">.</span></span><span class="token class-name">ExtensionLoader</span><span class="token punctuation">;</span>


<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Protocol</span>$<span class="token class-name">Adaptive</span> <span class="token keyword">implements</span> <span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>alibaba<span class="token punctuation">.</span>dubbo<span class="token punctuation">.</span>rpc<span class="token punctuation">.</span></span>Protocol</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">destroy</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">UnsupportedOperationException</span><span class="token punctuation">(</span>
            <span class="token string">"method public abstract void com.alibaba.dubbo.rpc.Protocol.destroy() of interface com.alibaba.dubbo.rpc.Protocol is not adaptive method!"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">getDefaultPort</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">UnsupportedOperationException</span><span class="token punctuation">(</span>
            <span class="token string">"method public abstract int com.alibaba.dubbo.rpc.Protocol.getDefaultPort() of interface com.alibaba.dubbo.rpc.Protocol is not adaptive method!"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>alibaba<span class="token punctuation">.</span>dubbo<span class="token punctuation">.</span>rpc<span class="token punctuation">.</span></span>Exporter</span> <span class="token function">export</span><span class="token punctuation">(</span>
        <span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>alibaba<span class="token punctuation">.</span>dubbo<span class="token punctuation">.</span>rpc<span class="token punctuation">.</span></span>Invoker</span> arg0<span class="token punctuation">)</span>
        <span class="token keyword">throws</span> <span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>alibaba<span class="token punctuation">.</span>dubbo<span class="token punctuation">.</span>rpc<span class="token punctuation">.</span></span>RpcException</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>arg0 <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">IllegalArgumentException</span><span class="token punctuation">(</span>
                <span class="token string">"com.alibaba.dubbo.rpc.Invoker argument == null"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span>arg0<span class="token punctuation">.</span><span class="token function">getUrl</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">IllegalArgumentException</span><span class="token punctuation">(</span>
                <span class="token string">"com.alibaba.dubbo.rpc.Invoker argument getUrl() == null"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>alibaba<span class="token punctuation">.</span>dubbo<span class="token punctuation">.</span>common<span class="token punctuation">.</span></span>URL</span> url <span class="token operator">=</span> arg0<span class="token punctuation">.</span><span class="token function">getUrl</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">String</span> extName <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token punctuation">(</span>url<span class="token punctuation">.</span><span class="token function">getProtocol</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token operator">?</span> <span class="token string">"dubbo"</span>
                                                      <span class="token operator">:</span> url<span class="token punctuation">.</span><span class="token function">getProtocol</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span>extName <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">IllegalStateException</span><span class="token punctuation">(</span>
                <span class="token string">"Fail to get extension(com.alibaba.dubbo.rpc.Protocol) name from url("</span> <span class="token operator">+</span>
                url<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">") use keys([protocol])"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>alibaba<span class="token punctuation">.</span>dubbo<span class="token punctuation">.</span>rpc<span class="token punctuation">.</span></span>Protocol</span> extension <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>alibaba<span class="token punctuation">.</span>dubbo<span class="token punctuation">.</span>rpc<span class="token punctuation">.</span></span>Protocol</span><span class="token punctuation">)</span> <span class="token class-name">ExtensionLoader</span><span class="token punctuation">.</span><span class="token function">getExtensionLoader</span><span class="token punctuation">(</span><span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>alibaba<span class="token punctuation">.</span>dubbo<span class="token punctuation">.</span>rpc<span class="token punctuation">.</span></span>Protocol</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span>
                                                                                                   <span class="token punctuation">.</span><span class="token function">getExtension</span><span class="token punctuation">(</span>extName<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">return</span> extension<span class="token punctuation">.</span><span class="token function">export</span><span class="token punctuation">(</span>arg0<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>alibaba<span class="token punctuation">.</span>dubbo<span class="token punctuation">.</span>rpc<span class="token punctuation">.</span></span>Invoker</span> <span class="token function">refer</span><span class="token punctuation">(</span><span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Class</span> arg0<span class="token punctuation">,</span>
        <span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>alibaba<span class="token punctuation">.</span>dubbo<span class="token punctuation">.</span>common<span class="token punctuation">.</span></span>URL</span> arg1<span class="token punctuation">)</span>
        <span class="token keyword">throws</span> <span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>alibaba<span class="token punctuation">.</span>dubbo<span class="token punctuation">.</span>rpc<span class="token punctuation">.</span></span>RpcException</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>arg1 <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">IllegalArgumentException</span><span class="token punctuation">(</span><span class="token string">"url == null"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>alibaba<span class="token punctuation">.</span>dubbo<span class="token punctuation">.</span>common<span class="token punctuation">.</span></span>URL</span> url <span class="token operator">=</span> arg1<span class="token punctuation">;</span>
      <span class="token comment">// 其实前面所说的逻辑就在这里呈现了</span>
        <span class="token class-name">String</span> extName <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token punctuation">(</span>url<span class="token punctuation">.</span><span class="token function">getProtocol</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token operator">?</span> <span class="token string">"dubbo"</span>
                                                      <span class="token operator">:</span> url<span class="token punctuation">.</span><span class="token function">getProtocol</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span>extName <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">IllegalStateException</span><span class="token punctuation">(</span>
                <span class="token string">"Fail to get extension(com.alibaba.dubbo.rpc.Protocol) name from url("</span> <span class="token operator">+</span>
                url<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">") use keys([protocol])"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
				<span class="token comment">// 在这就是实际的通过dubbo 的 spi 去加载实际对应的扩展</span>
        <span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>alibaba<span class="token punctuation">.</span>dubbo<span class="token punctuation">.</span>rpc<span class="token punctuation">.</span></span>Protocol</span> extension <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>alibaba<span class="token punctuation">.</span>dubbo<span class="token punctuation">.</span>rpc<span class="token punctuation">.</span></span>Protocol</span><span class="token punctuation">)</span> <span class="token class-name">ExtensionLoader</span><span class="token punctuation">.</span><span class="token function">getExtensionLoader</span><span class="token punctuation">(</span><span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>alibaba<span class="token punctuation">.</span>dubbo<span class="token punctuation">.</span>rpc<span class="token punctuation">.</span></span>Protocol</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span>
                                                                                                   <span class="token punctuation">.</span><span class="token function">getExtension</span><span class="token punctuation">(</span>extName<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">return</span> extension<span class="token punctuation">.</span><span class="token function">refer</span><span class="token punctuation">(</span>arg0<span class="token punctuation">,</span> arg1<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
]]></content>
      <categories>
        <category>Java</category>
        <category>Dubbo - RPC - SPI</category>
        <category>Dubbo</category>
        <category>SPI</category>
        <category>Adaptive</category>
      </categories>
      <tags>
        <tag>Java</tag>
        <tag>Dubbo</tag>
        <tag>RPC</tag>
        <tag>SPI</tag>
        <tag>Adaptive</tag>
        <tag>自适应拓展</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊 Dubbo 的 SPI</title>
    <url>/2020/05/31/%E8%81%8A%E8%81%8A-Dubbo-%E7%9A%84-SPI/</url>
    <content><![CDATA[<p>SPI全称是Service Provider Interface，咋眼看跟api是不是有点相似，api是application interface，这两个其实在某些方面有类似的地方，也有蛮大的区别，比如我们基于 dubbo 的微服务，一般我们可以提供服务，然后非泛化调用的话，我们可以把 api 包提供给应用调用方，他们根据接口签名传对应参数并配置好对应的服务发现如 zk 等就可以调用我们的服务了，然后 spi 会有点类似但是是反过来的关系，相当于是一种规范，比如我约定完成这个功能需要两个有两个接口，一个是连接的，一个是断开的，其实就可以用 jdbc 的驱动举例，比较老套了，然后各个厂家去做具体的实现吧，到时候根据我接口的全限定名的文件来加载实际的实现类，然后运行的时候调用对应实现类的方法就完了</p>
<p><img data-src="https://mystore-1255223546.cos.ap-chengdu.myqcloud.com/uPic/3sKdpg.png" alt="3sKdpg"></p>
<p>看上面的图，<code>java.sql.Driver</code>就是 spi，对应在classpath 的 META-INF/services 目录下的这个文件，里边的内容就是具体的实现类</p>
<p><img data-src="https://mystore-1255223546.cos.ap-chengdu.myqcloud.com/uPic/1590735097909.jpg" alt="1590735097909"></p>
<p>简单介绍了 Java的 SPI，再来说说 dubbo 的，dubbo 中为啥要用 SPI 呢，主要是为了框架的可扩展性和性能方面的考虑，比如协议层 dubbo 默认使用 dubbo 协议，同时也支持很多其他协议，也支持用户自己实现协议，那么跟 Java 的 SPI 会有什么区别呢，我们也来看个文件</p>
<p><img data-src="https://mystore-1255223546.cos.ap-chengdu.myqcloud.com/uPic/bqxWMp.png" alt="bqxWMp"></p>
<p>是不是看着很想，又有点不一样，在 Java 的 SPI 配置文件里每一行只有一个实现类的全限定名，在 Dubbo的 SPI配置文件中是 key=value 的形式，我们只需要对应的 key 就能加载对应的实现，</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">/**
     * 返回指定名字的扩展。如果指定名字的扩展不存在，则抛异常 &#123;@link IllegalStateException&#125;.
     *
     * @param name
     * @return
     */</span>
	<span class="token annotation punctuation">@SuppressWarnings</span><span class="token punctuation">(</span><span class="token string">"unchecked"</span><span class="token punctuation">)</span>
	<span class="token keyword">public</span> <span class="token class-name">T</span> <span class="token function">getExtension</span><span class="token punctuation">(</span><span class="token class-name">String</span> name<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
		<span class="token keyword">if</span> <span class="token punctuation">(</span>name <span class="token operator">==</span> <span class="token keyword">null</span> <span class="token operator">||</span> name<span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span>
		    <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">IllegalArgumentException</span><span class="token punctuation">(</span><span class="token string">"Extension name == null"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token string">"true"</span><span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
		    <span class="token keyword">return</span> <span class="token function">getDefaultExtension</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token punctuation">&#125;</span>
		<span class="token class-name">Holder</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Object</span><span class="token punctuation">></span></span> holder <span class="token operator">=</span> cachedInstances<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token keyword">if</span> <span class="token punctuation">(</span>holder <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
		    cachedInstances<span class="token punctuation">.</span><span class="token function">putIfAbsent</span><span class="token punctuation">(</span>name<span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">Holder</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Object</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		    holder <span class="token operator">=</span> cachedInstances<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token punctuation">&#125;</span>
		<span class="token class-name">Object</span> instance <span class="token operator">=</span> holder<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token keyword">if</span> <span class="token punctuation">(</span>instance <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
		    <span class="token keyword">synchronized</span> <span class="token punctuation">(</span>holder<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	            instance <span class="token operator">=</span> holder<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	            <span class="token keyword">if</span> <span class="token punctuation">(</span>instance <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	                instance <span class="token operator">=</span> <span class="token function">createExtension</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span>
	                holder<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span>instance<span class="token punctuation">)</span><span class="token punctuation">;</span>
	            <span class="token punctuation">&#125;</span>
	        <span class="token punctuation">&#125;</span>
		<span class="token punctuation">&#125;</span>
		<span class="token keyword">return</span> <span class="token punctuation">(</span><span class="token class-name">T</span><span class="token punctuation">)</span> instance<span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这里其实就可以看出来第二个不同点了，就是这个<code>cachedInstances</code>，第一个是不用像 Java 原生的 SPI 那样去遍历加载对应的服务类，只需要通过 key 去寻找，并且寻找的时候会先从缓存的对象里去取，还有就是注意下这里的 DCL(double check lock)</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@SuppressWarnings</span><span class="token punctuation">(</span><span class="token string">"unchecked"</span><span class="token punctuation">)</span>
    <span class="token keyword">private</span> <span class="token class-name">T</span> <span class="token function">createExtension</span><span class="token punctuation">(</span><span class="token class-name">String</span> name<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span> clazz <span class="token operator">=</span> <span class="token function">getExtensionClasses</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>clazz <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">throw</span> <span class="token function">findException</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">T</span> instance <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">T</span><span class="token punctuation">)</span> EXTENSION_INSTANCES<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span>clazz<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>instance <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                EXTENSION_INSTANCES<span class="token punctuation">.</span><span class="token function">putIfAbsent</span><span class="token punctuation">(</span>clazz<span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token class-name">T</span><span class="token punctuation">)</span> clazz<span class="token punctuation">.</span><span class="token function">newInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                instance <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">T</span><span class="token punctuation">)</span> EXTENSION_INSTANCES<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span>clazz<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
            <span class="token function">injectExtension</span><span class="token punctuation">(</span>instance<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">Set</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Class</span><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span><span class="token punctuation">></span></span> wrapperClasses <span class="token operator">=</span> cachedWrapperClasses<span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>wrapperClasses <span class="token operator">!=</span> <span class="token keyword">null</span> <span class="token operator">&amp;&amp;</span> wrapperClasses<span class="token punctuation">.</span><span class="token function">size</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">></span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span> wrapperClass <span class="token operator">:</span> wrapperClasses<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    instance <span class="token operator">=</span> <span class="token function">injectExtension</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token class-name">T</span><span class="token punctuation">)</span> wrapperClass<span class="token punctuation">.</span><span class="token function">getConstructor</span><span class="token punctuation">(</span>type<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">newInstance</span><span class="token punctuation">(</span>instance<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span>
            <span class="token keyword">return</span> instance<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Throwable</span> t<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">IllegalStateException</span><span class="token punctuation">(</span><span class="token string">"Extension instance(name: "</span> <span class="token operator">+</span> name <span class="token operator">+</span> <span class="token string">", class: "</span> <span class="token operator">+</span>
                    type <span class="token operator">+</span> <span class="token string">")  could not be instantiated: "</span> <span class="token operator">+</span> t<span class="token punctuation">.</span><span class="token function">getMessage</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> t<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>然后就是创建扩展了，这里如果 wrapperClasses 就会遍历生成wrapper实例，并做 setter 依赖注入，但是这里cachedWrapperClasses的来源还是有点搞不清楚，得再看下 com.alibaba.dubbo.common.extension.ExtensionLoader#loadFile的具体逻辑<br>又看了遍新的代码，这个函数被抽出来了</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">/**
    * test if clazz is a wrapper class
    * &lt;p>
    * which has Constructor with given class type as its only argument
    */</span>
   <span class="token keyword">private</span> <span class="token keyword">boolean</span> <span class="token function">isWrapperClass</span><span class="token punctuation">(</span><span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span> clazz<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
       <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
           clazz<span class="token punctuation">.</span><span class="token function">getConstructor</span><span class="token punctuation">(</span>type<span class="token punctuation">)</span><span class="token punctuation">;</span>
           <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
       <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">NoSuchMethodException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
           <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
       <span class="token punctuation">&#125;</span>
   <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>是否是 wrapperClass 其实就看构造函数的。</p>
]]></content>
      <categories>
        <category>Java</category>
        <category>Dubbo - RPC - SPI</category>
        <category>Dubbo</category>
        <category>SPI</category>
      </categories>
      <tags>
        <tag>Java</tag>
        <tag>Dubbo</tag>
        <tag>RPC</tag>
        <tag>SPI</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊 Dubbo 的容错机制</title>
    <url>/2020/11/22/%E8%81%8A%E8%81%8A-Dubbo-%E7%9A%84%E5%AE%B9%E9%94%99%E6%9C%BA%E5%88%B6/</url>
    <content><![CDATA[<p>之前看了 dubbo 的一些代码，在学习过程中，主要关注那些比较“高级”的内容，SPI，自适应扩展等，却忘了一些作为一个 rpc 框架最核心需要的部分，比如如何通信，序列化，网络，容错机制等等，因为其实这个最核心的就是远程调用，自适应扩展其实就是让代码可扩展性，可读性，更优雅等，写的搓一点其实也问题不大，但是一个合适的通信协议，序列化方法，如何容错等却是真正保证是一个 rpc 框架最重要的要素。<br>首先来看这张图<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/cluster.jpg" alt="cluster"><br>在集群调用失败时，Dubbo 提供了多种容错方案，缺省为 failover 重试。<br>各节点关系：</p>
<ul>
<li>这里的 <code>Invoker</code> 是 <code>Provider</code> 的一个可调用 <code>Service</code> 的抽象，<code>Invoker</code> 封装了 <code>Provider</code> 地址及 <code>Service</code> 接口信息</li>
<li><code>Directory</code> 代表多个 <code>Invoker</code>，可以把它看成 <code>List&lt;Invoker&gt;</code> ，但与 <code>List</code> 不同的是，它的值可能是动态变化的，比如注册中心推送变更</li>
<li><code>Cluster</code> 将 <code>Directory</code> 中的多个 <code>Invoker</code> 伪装成一个 <code>Invoker</code>，对上层透明，伪装过程包含了容错逻辑，调用失败后，重试另一个</li>
<li><code>Router</code> 负责从多个 <code>Invoker</code> 中按路由规则选出子集，比如读写分离，应用隔离等</li>
<li><code>LoadBalance</code> 负责从多个 <code>Invoker</code> 中选出具体的一个用于本次调用，选的过程包含了负载均衡算法，调用失败后，需要重选</li>
</ul>
<h2 id="集群容错模式"><a href="#集群容错模式" class="headerlink" title="集群容错模式"></a>集群容错模式</h2><h3 id="Failover-Cluster"><a href="#Failover-Cluster" class="headerlink" title="Failover Cluster"></a>Failover Cluster</h3><p>失败自动切换，当出现失败，重试其它服务器 1。通常用于读操作，但重试会带来更长延迟。可通过 retries=”2” 来设置重试次数(不含第一次)。</p>
<p>重试次数配置如下：</p>
<p>&lt;dubbo:service retries=”2” /&gt;<br>这里重点看下 <code>Failover Cluster</code>集群模式的实现  </p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">FailoverCluster</span> <span class="token keyword">implements</span> <span class="token class-name">Cluster</span> <span class="token punctuation">&#123;</span>

    <span class="token keyword">public</span> <span class="token keyword">final</span> <span class="token keyword">static</span> <span class="token class-name">String</span> NAME <span class="token operator">=</span> <span class="token string">"failover"</span><span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">></span></span> <span class="token class-name">Invoker</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">></span></span> <span class="token function">join</span><span class="token punctuation">(</span><span class="token class-name">Directory</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">></span></span> directory<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">RpcException</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">FailoverClusterInvoker</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">></span></span><span class="token punctuation">(</span>directory<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这个代码就非常简单，重点需要看<code>FailoverClusterInvoker</code>里的代码，<code>FailoverClusterInvoker</code>继承了<code>AbstractClusterInvoker</code>类，其中invoke 方法是在抽象类里实现的</p>
<pre class="line-numbers language-Java" data-language="Java"><code class="language-Java">@Override
public Result invoke(final Invocation invocation) throws RpcException &#123;
    checkWhetherDestroyed();
    &#x2F;&#x2F; binding attachments into invocation.
    &#x2F;&#x2F; 绑定 attachments 到 invocation 中.
    Map&lt;String, Object&gt; contextAttachments &#x3D; RpcContext.getContext().getObjectAttachments();
    if (contextAttachments !&#x3D; null &amp;&amp; contextAttachments.size() !&#x3D; 0) &#123;
        ((RpcInvocation) invocation).addObjectAttachments(contextAttachments);
    &#125;
    &#x2F;&#x2F; 列举 Invoker
    List&lt;Invoker&lt;T&gt;&gt; invokers &#x3D; list(invocation);
    &#x2F;&#x2F; 加载 LoadBalance 负载均衡器
    LoadBalance loadbalance &#x3D; initLoadBalance(invokers, invocation);
    RpcUtils.attachInvocationIdIfAsync(getUrl(), invocation);
    &#x2F;&#x2F; 调用 实际的 doInvoke 进行后续操作
    return doInvoke(invocation, invokers, loadbalance);
&#125;
&#x2F;&#x2F; 这是个抽象方法，实际是由子类实现的
 protected abstract Result doInvoke(Invocation invocation, List&lt;Invoker&lt;T&gt;&gt; invokers,
                                       LoadBalance loadbalance) throws RpcException;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>然后重点就是<code>FailoverClusterInvoker</code>中的<code>doInvoke</code>方法了，其实它里面也就这么一个方法</p>
<pre class="line-numbers language-Java" data-language="Java"><code class="language-Java">@Override
    @SuppressWarnings(&#123;&quot;unchecked&quot;, &quot;rawtypes&quot;&#125;)
    public Result doInvoke(Invocation invocation, final List&lt;Invoker&lt;T&gt;&gt; invokers, LoadBalance loadbalance) throws RpcException &#123;
        List&lt;Invoker&lt;T&gt;&gt; copyInvokers &#x3D; invokers;
        checkInvokers(copyInvokers, invocation);
        String methodName &#x3D; RpcUtils.getMethodName(invocation);
        &#x2F;&#x2F; 获取重试次数，这里默认是 2 次，还有可以注意下后面的+1
        int len &#x3D; getUrl().getMethodParameter(methodName, RETRIES_KEY, DEFAULT_RETRIES) + 1;
        if (len &lt;&#x3D; 0) &#123;
            len &#x3D; 1;
        &#125;
        &#x2F;&#x2F; retry loop.
        RpcException le &#x3D; null; &#x2F;&#x2F; last exception.
        List&lt;Invoker&lt;T&gt;&gt; invoked &#x3D; new ArrayList&lt;Invoker&lt;T&gt;&gt;(copyInvokers.size()); &#x2F;&#x2F; invoked invokers.
        Set&lt;String&gt; providers &#x3D; new HashSet&lt;String&gt;(len);
        &#x2F;&#x2F; 循环调用，失败重试
        for (int i &#x3D; 0; i &lt; len; i++) &#123;
            &#x2F;&#x2F;Reselect before retry to avoid a change of candidate &#96;invokers&#96;.
            &#x2F;&#x2F;NOTE: if &#96;invokers&#96; changed, then &#96;invoked&#96; also lose accuracy.
            if (i &gt; 0) &#123;
                checkWhetherDestroyed();
                &#x2F;&#x2F; 在进行重试前重新列举 Invoker，这样做的好处是，如果某个服务挂了，
                &#x2F;&#x2F; 通过调用 list 可得到最新可用的 Invoker 列表
                copyInvokers &#x3D; list(invocation);
                &#x2F;&#x2F; check again
                &#x2F;&#x2F; 对 copyinvokers 进行判空检查
                checkInvokers(copyInvokers, invocation);
            &#125;
            &#x2F;&#x2F; 通过负载均衡来选择 invoker
            Invoker&lt;T&gt; invoker &#x3D; select(loadbalance, invocation, copyInvokers, invoked);
            &#x2F;&#x2F; 将其添加到 invoker 到 invoked 列表中
            invoked.add(invoker);
            &#x2F;&#x2F; 设置上下文
            RpcContext.getContext().setInvokers((List) invoked);
            try &#123;
                &#x2F;&#x2F; 正式调用
                Result result &#x3D; invoker.invoke(invocation);
                if (le !&#x3D; null &amp;&amp; logger.isWarnEnabled()) &#123;
                    logger.warn(&quot;Although retry the method &quot; + methodName
                            + &quot; in the service &quot; + getInterface().getName()
                            + &quot; was successful by the provider &quot; + invoker.getUrl().getAddress()
                            + &quot;, but there have been failed providers &quot; + providers
                            + &quot; (&quot; + providers.size() + &quot;&#x2F;&quot; + copyInvokers.size()
                            + &quot;) from the registry &quot; + directory.getUrl().getAddress()
                            + &quot; on the consumer &quot; + NetUtils.getLocalHost()
                            + &quot; using the dubbo version &quot; + Version.getVersion() + &quot;. Last error is: &quot;
                            + le.getMessage(), le);
                &#125;
                return result;
            &#125; catch (RpcException e) &#123;
                if (e.isBiz()) &#123; &#x2F;&#x2F; biz exception.
                    throw e;
                &#125;
                le &#x3D; e;
            &#125; catch (Throwable e) &#123;
                le &#x3D; new RpcException(e.getMessage(), e);
            &#125; finally &#123;
                providers.add(invoker.getUrl().getAddress());
            &#125;
        &#125;
        throw new RpcException(le.getCode(), &quot;Failed to invoke the method &quot;
                + methodName + &quot; in the service &quot; + getInterface().getName()
                + &quot;. Tried &quot; + len + &quot; times of the providers &quot; + providers
                + &quot; (&quot; + providers.size() + &quot;&#x2F;&quot; + copyInvokers.size()
                + &quot;) from the registry &quot; + directory.getUrl().getAddress()
                + &quot; on the consumer &quot; + NetUtils.getLocalHost() + &quot; using the dubbo version &quot;
                + Version.getVersion() + &quot;. Last error is: &quot;
                + le.getMessage(), le.getCause() !&#x3D; null ? le.getCause() : le);
    &#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<h3 id="Failfast-Cluster"><a href="#Failfast-Cluster" class="headerlink" title="Failfast Cluster"></a>Failfast Cluster</h3><p>快速失败，只发起一次调用，失败立即报错。通常用于非幂等性的写操作，比如新增记录。</p>
<h3 id="Failsafe-Cluster"><a href="#Failsafe-Cluster" class="headerlink" title="Failsafe Cluster"></a>Failsafe Cluster</h3><p>失败安全，出现异常时，直接忽略。通常用于写入审计日志等操作。</p>
<h3 id="Failback-Cluster"><a href="#Failback-Cluster" class="headerlink" title="Failback Cluster"></a>Failback Cluster</h3><p>失败自动恢复，后台记录失败请求，定时重发。通常用于消息通知操作。</p>
<h3 id="Forking-Cluster"><a href="#Forking-Cluster" class="headerlink" title="Forking Cluster"></a>Forking Cluster</h3><p>并行调用多个服务器，只要一个成功即返回。通常用于实时性要求较高的读操作，但需要浪费更多服务资源。可通过 forks=”2” 来设置最大并行数。</p>
<h3 id="Broadcast-Cluster"><a href="#Broadcast-Cluster" class="headerlink" title="Broadcast Cluster"></a>Broadcast Cluster</h3><p>广播调用所有提供者，逐个调用，任意一台报错则报错 2。通常用于通知所有提供者更新缓存或日志等本地资源信息。</p>
]]></content>
      <categories>
        <category>Java</category>
        <category>Dubbo - RPC</category>
        <category>Dubbo</category>
        <category>容错机制</category>
      </categories>
      <tags>
        <tag>Java</tag>
        <tag>Dubbo</tag>
        <tag>RPC</tag>
        <tag>容错机制</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊 Java 中绕不开的 Synchronized 关键字-二</title>
    <url>/2021/06/27/%E8%81%8A%E8%81%8A-Java-%E4%B8%AD%E7%BB%95%E4%B8%8D%E5%BC%80%E7%9A%84-Synchronized-%E5%85%B3%E9%94%AE%E5%AD%97-%E4%BA%8C/</url>
    <content><![CDATA[<h1 id="Java并发"><a href="#Java并发" class="headerlink" title="Java并发"></a>Java并发</h1><p>synchronized 的一些学习记录</p>
<p>jdk1.6 以后对 synchronized 进行了一些优化，包括偏向锁，轻量级锁，重量级锁等</p>
<p>这些锁的加锁方式大多跟对象头有关，我们可以查看 jdk 代码</p>
<p>首先对象头的位置注释</p>
<pre class="line-numbers language-c" data-language="c"><code class="language-c"><span class="token comment">// Bit-format of an object header (most significant first, big endian layout below):</span>
<span class="token comment">//</span>
<span class="token comment">//  32 bits:</span>
<span class="token comment">//  --------</span>
<span class="token comment">//             hash:25 ------------>| age:4    biased_lock:1 lock:2 (normal object)</span>
<span class="token comment">//             JavaThread*:23 epoch:2 age:4    biased_lock:1 lock:2 (biased object)</span>
<span class="token comment">//             size:32 ------------------------------------------>| (CMS free block)</span>
<span class="token comment">//             PromotedObject*:29 ---------->| promo_bits:3 ----->| (CMS promoted object)</span>
<span class="token comment">//</span>
<span class="token comment">//  64 bits:</span>
<span class="token comment">//  --------</span>
<span class="token comment">//  unused:25 hash:31 -->| unused:1   age:4    biased_lock:1 lock:2 (normal object)</span>
<span class="token comment">//  JavaThread*:54 epoch:2 unused:1   age:4    biased_lock:1 lock:2 (biased object)</span>
<span class="token comment">//  PromotedObject*:61 --------------------->| promo_bits:3 ----->| (CMS promoted object)</span>
<span class="token comment">//  size:64 ----------------------------------------------------->| (CMS free block)</span>
<span class="token comment">//</span>
<span class="token comment">//  unused:25 hash:31 -->| cms_free:1 age:4    biased_lock:1 lock:2 (COOPs &amp;&amp; normal object)</span>
<span class="token comment">//  JavaThread*:54 epoch:2 cms_free:1 age:4    biased_lock:1 lock:2 (COOPs &amp;&amp; biased object)</span>
<span class="token comment">//  narrowOop:32 unused:24 cms_free:1 unused:4 promo_bits:3 ----->| (COOPs &amp;&amp; CMS promoted object)</span>
<span class="token comment">//  unused:21 size:35 -->| cms_free:1 unused:7 ------------------>| (COOPs &amp;&amp; CMS free block)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<pre class="line-numbers language-c" data-language="c"><code class="language-c"><span class="token keyword">enum</span> <span class="token punctuation">&#123;</span> locked_value             <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">,</span>
         unlocked_value           <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">,</span>
         monitor_value            <span class="token operator">=</span> <span class="token number">2</span><span class="token punctuation">,</span>
         marked_value             <span class="token operator">=</span> <span class="token number">3</span><span class="token punctuation">,</span>
         biased_lock_pattern      <span class="token operator">=</span> <span class="token number">5</span>
<span class="token punctuation">&#125;</span><span class="token punctuation">;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>我们可以用 java jol库来查看对象头，通过一段简单的代码来看下</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ObjectHeaderDemo</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">L</span> l <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">L</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token class-name">ClassLayout</span><span class="token punctuation">.</span><span class="token function">parseInstance</span><span class="token punctuation">(</span>l<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toPrintable</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/Untitled.png" alt="Untitled"></p>
<p>然后可以看到打印输出，当然这里因为对齐方式，我们看到的其实顺序是反过来的，按最后三位去看，我们这是 001，好像偏向锁都没开，这里使用的是 jdk1.8，默认开始偏向锁的，其实这里有涉及到了一个配置，jdk1.8 中偏向锁会延迟 4 秒开启，可以通过添加启动参数 -XX:+PrintFlagsFinal，看到</p>
<p><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/%E5%81%8F%E5%90%91%E9%94%81%E5%BB%B6%E8%BF%9F.png" alt="偏向锁延迟"></p>
<p>因为在初始化的时候防止线程竞争有大量的偏向锁撤销升级，所以会延迟 4s 开启</p>
<p>我们再来延迟 5s 看看</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ObjectHeaderDemo</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span> <span class="token punctuation">&#123;</span>
				<span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>SECONDS<span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">L</span> l <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">L</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token class-name">ClassLayout</span><span class="token punctuation">.</span><span class="token function">parseInstance</span><span class="token punctuation">(</span>l<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toPrintable</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span> <span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/2LBKpX.jpg" alt="https://gitee.com/nicksxs/images/raw/master/uPic/2LBKpX.jpg"></p>
<p>可以看到偏向锁设置已经开启了，我们来是一下加个偏向锁</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ObjectHeaderDemo</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>SECONDS<span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">L</span> l <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">L</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token class-name">ClassLayout</span><span class="token punctuation">.</span><span class="token function">parseInstance</span><span class="token punctuation">(</span>l<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toPrintable</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">synchronized</span> <span class="token punctuation">(</span>l<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"1\n"</span> <span class="token operator">+</span> <span class="token class-name">ClassLayout</span><span class="token punctuation">.</span><span class="token function">parseInstance</span><span class="token punctuation">(</span>l<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toPrintable</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">synchronized</span> <span class="token punctuation">(</span>l<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"2\n"</span> <span class="token operator">+</span> <span class="token class-name">ClassLayout</span><span class="token punctuation">.</span><span class="token function">parseInstance</span><span class="token punctuation">(</span>l<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toPrintable</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
		<span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>看下运行结果</p>
<p><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/V2l78m.png" alt="https://gitee.com/nicksxs/images/raw/master/uPic/V2l78m.png"></p>
<p>可以看到是加上了 101 = 5 也就是偏向锁，后面是线程 id</p>
<p>当我再使用一个线程来竞争这个锁的时候</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ObjectHeaderDemo</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>SECONDS<span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">L</span> l <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">L</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token class-name">ClassLayout</span><span class="token punctuation">.</span><span class="token function">parseInstance</span><span class="token punctuation">(</span>l<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toPrintable</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">synchronized</span> <span class="token punctuation">(</span>l<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"1\n"</span> <span class="token operator">+</span> <span class="token class-name">ClassLayout</span><span class="token punctuation">.</span><span class="token function">parseInstance</span><span class="token punctuation">(</span>l<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toPrintable</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
				<span class="token class-name">Thread</span> thread1 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Thread</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token annotation punctuation">@Override</span>
            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                    <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>SECONDS<span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">5L</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
                <span class="token keyword">synchronized</span> <span class="token punctuation">(</span>l<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"thread1 获取锁成功"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token class-name">ClassLayout</span><span class="token punctuation">.</span><span class="token function">parseInstance</span><span class="token punctuation">(</span>l<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toPrintable</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                        <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>SECONDS<span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">5L</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">;</span>
				thread1<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/bRMvlR.png" alt="https://gitee.com/nicksxs/images/raw/master/uPic/bRMvlR.png"></p>
<p>可以看到变成了轻量级锁，在线程没有争抢，只是进行了切换，就会使用轻量级锁，当两个线程在竞争了，就又会升级成重量级锁</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ObjectHeaderDemo</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>SECONDS<span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">L</span> l <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">L</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token class-name">ClassLayout</span><span class="token punctuation">.</span><span class="token function">parseInstance</span><span class="token punctuation">(</span>l<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toPrintable</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">synchronized</span> <span class="token punctuation">(</span>l<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"1\n"</span> <span class="token operator">+</span> <span class="token class-name">ClassLayout</span><span class="token punctuation">.</span><span class="token function">parseInstance</span><span class="token punctuation">(</span>l<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toPrintable</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token class-name">Thread</span> thread1 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Thread</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token annotation punctuation">@Override</span>
            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                    <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>SECONDS<span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">5L</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
                <span class="token keyword">synchronized</span> <span class="token punctuation">(</span>l<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"thread1 获取锁成功"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token class-name">ClassLayout</span><span class="token punctuation">.</span><span class="token function">parseInstance</span><span class="token punctuation">(</span>l<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toPrintable</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                        <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>SECONDS<span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">5L</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">;</span>
        <span class="token class-name">Thread</span> thread2 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Thread</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token annotation punctuation">@Override</span>
            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                    <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>SECONDS<span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">5L</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
                <span class="token keyword">synchronized</span> <span class="token punctuation">(</span>l<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"thread2 获取锁成功"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token class-name">ClassLayout</span><span class="token punctuation">.</span><span class="token function">parseInstance</span><span class="token punctuation">(</span>l<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toPrintable</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">;</span>
        thread1<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        thread2<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>

<span class="token keyword">class</span> <span class="token class-name">L</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">private</span> <span class="token keyword">boolean</span> myboolean <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/LMzMtR.png" alt="https://gitee.com/nicksxs/images/raw/master/uPic/LMzMtR.png"></p>
<p>可以看到变成了重量级锁。</p>
]]></content>
      <categories>
        <category>Java</category>
      </categories>
      <tags>
        <tag>Java</tag>
        <tag>Synchronized</tag>
        <tag>偏向锁</tag>
        <tag>轻量级锁</tag>
        <tag>重量级锁</tag>
        <tag>自旋</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊 Java 中绕不开的 Synchronized 关键字</title>
    <url>/2021/06/20/%E8%81%8A%E8%81%8A-Java-%E4%B8%AD%E7%BB%95%E4%B8%8D%E5%BC%80%E7%9A%84-Synchronized-%E5%85%B3%E9%94%AE%E5%AD%97/</url>
    <content><![CDATA[<p>Synchronized 关键字在 Java 的并发体系里也是非常重要的一个内容，首先比较常规的是知道它使用的方式，可以锁对象，可以锁代码块，也可以锁方法，看一个简单的 demo</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">SynchronizedDemo</span> <span class="token punctuation">&#123;</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">SynchronizedDemo</span> synchronizedDemo <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">SynchronizedDemo</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        synchronizedDemo<span class="token punctuation">.</span><span class="token function">lockMethod</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token keyword">synchronized</span> <span class="token keyword">void</span> <span class="token function">lockMethod</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"here i'm locked"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">lockSynchronizedDemo</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">synchronized</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"here lock class"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>然后来查看反编译结果，其实代码（日光）之下并无新事，即使是完全不懂的也可以通过一些词义看出一些意义</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">  <span class="token class-name">Last</span> modified <span class="token number">2021</span>年<span class="token number">6</span>月<span class="token number">20</span>日<span class="token punctuation">;</span> size <span class="token number">729</span> bytes
  MD5 checksum dd9c529863bd7ff839a95481db578ad9
  <span class="token class-name">Compiled</span> from <span class="token string">"SynchronizedDemo.java"</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">SynchronizedDemo</span>
  minor version<span class="token operator">:</span> <span class="token number">0</span>
  major version<span class="token operator">:</span> <span class="token number">53</span>
  flags<span class="token operator">:</span> <span class="token punctuation">(</span><span class="token number">0x0021</span><span class="token punctuation">)</span> ACC_PUBLIC<span class="token punctuation">,</span> ACC_SUPER
  this_class<span class="token operator">:</span> #<span class="token number">2</span>                          <span class="token comment">// SynchronizedDemo</span>
  super_class<span class="token operator">:</span> #<span class="token number">9</span>                         <span class="token comment">// java/lang/Object</span>
  interfaces<span class="token operator">:</span> <span class="token number">0</span><span class="token punctuation">,</span> fields<span class="token operator">:</span> <span class="token number">0</span><span class="token punctuation">,</span> methods<span class="token operator">:</span> <span class="token number">4</span><span class="token punctuation">,</span> attributes<span class="token operator">:</span> <span class="token number">1</span>
<span class="token class-name">Constant</span> pool<span class="token operator">:</span>
   #<span class="token number">1</span> <span class="token operator">=</span> <span class="token class-name">Methodref</span>          #<span class="token number">9.</span>#<span class="token number">22</span>         <span class="token comment">// java/lang/Object."&lt;init>":()V</span>
   #<span class="token number">2</span> <span class="token operator">=</span> <span class="token class-name">Class</span>              #<span class="token number">23</span>            <span class="token comment">// SynchronizedDemo</span>
   #<span class="token number">3</span> <span class="token operator">=</span> <span class="token class-name">Methodref</span>          #<span class="token number">2.</span>#<span class="token number">22</span>         <span class="token comment">// SynchronizedDemo."&lt;init>":()V</span>
   #<span class="token number">4</span> <span class="token operator">=</span> <span class="token class-name">Methodref</span>          #<span class="token number">2.</span>#<span class="token number">24</span>         <span class="token comment">// SynchronizedDemo.lockMethod:()V</span>
   #<span class="token number">5</span> <span class="token operator">=</span> <span class="token class-name">Fieldref</span>           #<span class="token number">25.</span>#<span class="token number">26</span>        <span class="token comment">// java/lang/System.out:Ljava/io/PrintStream;</span>
   #<span class="token number">6</span> <span class="token operator">=</span> <span class="token class-name">String</span>             #<span class="token number">27</span>            <span class="token comment">// here i\'m locked</span>
   #<span class="token number">7</span> <span class="token operator">=</span> <span class="token class-name">Methodref</span>          #<span class="token number">28.</span>#<span class="token number">29</span>        <span class="token comment">// java/io/PrintStream.println:(Ljava/lang/String;)V</span>
   #<span class="token number">8</span> <span class="token operator">=</span> <span class="token class-name">String</span>             #<span class="token number">30</span>            <span class="token comment">// here lock class</span>
   #<span class="token number">9</span> <span class="token operator">=</span> <span class="token class-name">Class</span>              #<span class="token number">31</span>            <span class="token comment">// java/lang/Object</span>
  #<span class="token number">10</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               <span class="token generics"><span class="token punctuation">&lt;</span>init<span class="token punctuation">></span></span>
  #<span class="token number">11</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               <span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token class-name">V</span>
  #<span class="token number">12</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               <span class="token class-name">Code</span>
  #<span class="token number">13</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               <span class="token class-name">LineNumberTable</span>
  #<span class="token number">14</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               main
  #<span class="token number">15</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               <span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token class-name">Ljava</span><span class="token operator">/</span>lang<span class="token operator">/</span><span class="token class-name">String</span><span class="token punctuation">;</span><span class="token punctuation">)</span><span class="token class-name">V</span>
  #<span class="token number">16</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               lockMethod
  #<span class="token number">17</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               lockSynchronizedDemo
  #<span class="token number">18</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               <span class="token class-name">StackMapTable</span>
  #<span class="token number">19</span> <span class="token operator">=</span> <span class="token class-name">Class</span>              #<span class="token number">32</span>            <span class="token comment">// java/lang/Throwable</span>
  #<span class="token number">20</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               <span class="token class-name">SourceFile</span>
  #<span class="token number">21</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               <span class="token class-name">SynchronizedDemo</span><span class="token punctuation">.</span>java
  #<span class="token number">22</span> <span class="token operator">=</span> <span class="token class-name">NameAndType</span>        #<span class="token number">10</span><span class="token operator">:</span>#<span class="token number">11</span>        <span class="token comment">// "&lt;init>":()V</span>
  #<span class="token number">23</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               <span class="token class-name">SynchronizedDemo</span>
  #<span class="token number">24</span> <span class="token operator">=</span> <span class="token class-name">NameAndType</span>        #<span class="token number">16</span><span class="token operator">:</span>#<span class="token number">11</span>        <span class="token comment">// lockMethod:()V</span>
  #<span class="token number">25</span> <span class="token operator">=</span> <span class="token class-name">Class</span>              #<span class="token number">33</span>            <span class="token comment">// java/lang/System</span>
  #<span class="token number">26</span> <span class="token operator">=</span> <span class="token class-name">NameAndType</span>        #<span class="token number">34</span><span class="token operator">:</span>#<span class="token number">35</span>        <span class="token comment">// out:Ljava/io/PrintStream;</span>
  #<span class="token number">27</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               here i\'m locked
  #<span class="token number">28</span> <span class="token operator">=</span> <span class="token class-name">Class</span>              #<span class="token number">36</span>            <span class="token comment">// java/io/PrintStream</span>
  #<span class="token number">29</span> <span class="token operator">=</span> <span class="token class-name">NameAndType</span>        #<span class="token number">37</span><span class="token operator">:</span>#<span class="token number">38</span>        <span class="token comment">// println:(Ljava/lang/String;)V</span>
  #<span class="token number">30</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               here lock <span class="token keyword">class</span>
  #<span class="token number">31</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               java<span class="token operator">/</span>lang<span class="token operator">/</span><span class="token class-name">Object</span>
  #<span class="token number">32</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               java<span class="token operator">/</span>lang<span class="token operator">/</span><span class="token class-name">Throwable</span>
  #<span class="token number">33</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               java<span class="token operator">/</span>lang<span class="token operator">/</span><span class="token class-name">System</span>
  #<span class="token number">34</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               out
  #<span class="token number">35</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               <span class="token class-name">Ljava</span><span class="token operator">/</span>io<span class="token operator">/</span><span class="token class-name">PrintStream</span><span class="token punctuation">;</span>
  #<span class="token number">36</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               java<span class="token operator">/</span>io<span class="token operator">/</span><span class="token class-name">PrintStream</span>
  #<span class="token number">37</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               println
  #<span class="token number">38</span> <span class="token operator">=</span> <span class="token class-name">Utf8</span>               <span class="token punctuation">(</span><span class="token class-name">Ljava</span><span class="token operator">/</span>lang<span class="token operator">/</span><span class="token class-name">String</span><span class="token punctuation">;</span><span class="token punctuation">)</span><span class="token class-name">V</span>
<span class="token punctuation">&#123;</span>
  <span class="token keyword">public</span> <span class="token class-name">SynchronizedDemo</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    descriptor<span class="token operator">:</span> <span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token class-name">V</span>
    flags<span class="token operator">:</span> <span class="token punctuation">(</span><span class="token number">0x0001</span><span class="token punctuation">)</span> ACC_PUBLIC
    <span class="token class-name">Code</span><span class="token operator">:</span>
      stack<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">,</span> locals<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">,</span> args_size<span class="token operator">=</span><span class="token number">1</span>
         <span class="token number">0</span><span class="token operator">:</span> aload_0
         <span class="token number">1</span><span class="token operator">:</span> invokespecial #<span class="token number">1</span>                  <span class="token comment">// Method java/lang/Object."&lt;init>":()V</span>
         <span class="token number">4</span><span class="token operator">:</span> <span class="token keyword">return</span>
      <span class="token class-name">LineNumberTable</span><span class="token operator">:</span>
        line <span class="token number">5</span><span class="token operator">:</span> <span class="token number">0</span>

  <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>String</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    descriptor<span class="token operator">:</span> <span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token class-name">Ljava</span><span class="token operator">/</span>lang<span class="token operator">/</span><span class="token class-name">String</span><span class="token punctuation">;</span><span class="token punctuation">)</span><span class="token class-name">V</span>
    flags<span class="token operator">:</span> <span class="token punctuation">(</span><span class="token number">0x0009</span><span class="token punctuation">)</span> ACC_PUBLIC<span class="token punctuation">,</span> ACC_STATIC
    <span class="token class-name">Code</span><span class="token operator">:</span>
      stack<span class="token operator">=</span><span class="token number">2</span><span class="token punctuation">,</span> locals<span class="token operator">=</span><span class="token number">2</span><span class="token punctuation">,</span> args_size<span class="token operator">=</span><span class="token number">1</span>
         <span class="token number">0</span><span class="token operator">:</span> <span class="token keyword">new</span>           #<span class="token number">2</span>                  <span class="token comment">// class SynchronizedDemo</span>
         <span class="token number">3</span><span class="token operator">:</span> dup
         <span class="token number">4</span><span class="token operator">:</span> invokespecial #<span class="token number">3</span>                  <span class="token comment">// Method "&lt;init>":()V</span>
         <span class="token number">7</span><span class="token operator">:</span> astore_1
         <span class="token number">8</span><span class="token operator">:</span> aload_1
         <span class="token number">9</span><span class="token operator">:</span> invokevirtual #<span class="token number">4</span>                  <span class="token comment">// Method lockMethod:()V</span>
        <span class="token number">12</span><span class="token operator">:</span> <span class="token keyword">return</span>
      <span class="token class-name">LineNumberTable</span><span class="token operator">:</span>
        line <span class="token number">8</span><span class="token operator">:</span> <span class="token number">0</span>
        line <span class="token number">9</span><span class="token operator">:</span> <span class="token number">8</span>
        line <span class="token number">10</span><span class="token operator">:</span> <span class="token number">12</span>

  <span class="token keyword">public</span> <span class="token keyword">synchronized</span> <span class="token keyword">void</span> <span class="token function">lockMethod</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    descriptor<span class="token operator">:</span> <span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token class-name">V</span>
    flags<span class="token operator">:</span> <span class="token punctuation">(</span><span class="token number">0x0021</span><span class="token punctuation">)</span> ACC_PUBLIC<span class="token punctuation">,</span> ACC_SYNCHRONIZED
    <span class="token class-name">Code</span><span class="token operator">:</span>
      stack<span class="token operator">=</span><span class="token number">2</span><span class="token punctuation">,</span> locals<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">,</span> args_size<span class="token operator">=</span><span class="token number">1</span>
         <span class="token number">0</span><span class="token operator">:</span> getstatic     #<span class="token number">5</span>                  <span class="token comment">// Field java/lang/System.out:Ljava/io/PrintStream;</span>
         <span class="token number">3</span><span class="token operator">:</span> ldc           #<span class="token number">6</span>                  <span class="token comment">// String here i\'m locked</span>
         <span class="token number">5</span><span class="token operator">:</span> invokevirtual #<span class="token number">7</span>                  <span class="token comment">// Method java/io/PrintStream.println:(Ljava/lang/String;)V</span>
         <span class="token number">8</span><span class="token operator">:</span> <span class="token keyword">return</span>
      <span class="token class-name">LineNumberTable</span><span class="token operator">:</span>
        line <span class="token number">13</span><span class="token operator">:</span> <span class="token number">0</span>
        line <span class="token number">14</span><span class="token operator">:</span> <span class="token number">8</span>

  <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">lockSynchronizedDemo</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    descriptor<span class="token operator">:</span> <span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token class-name">V</span>
    flags<span class="token operator">:</span> <span class="token punctuation">(</span><span class="token number">0x0001</span><span class="token punctuation">)</span> ACC_PUBLIC
    <span class="token class-name">Code</span><span class="token operator">:</span>
      stack<span class="token operator">=</span><span class="token number">2</span><span class="token punctuation">,</span> locals<span class="token operator">=</span><span class="token number">3</span><span class="token punctuation">,</span> args_size<span class="token operator">=</span><span class="token number">1</span>
         <span class="token number">0</span><span class="token operator">:</span> aload_0
         <span class="token number">1</span><span class="token operator">:</span> dup
         <span class="token number">2</span><span class="token operator">:</span> astore_1
         <span class="token number">3</span><span class="token operator">:</span> monitorenter
         <span class="token number">4</span><span class="token operator">:</span> getstatic     #<span class="token number">5</span>                  <span class="token comment">// Field java/lang/System.out:Ljava/io/PrintStream;</span>
         <span class="token number">7</span><span class="token operator">:</span> ldc           #<span class="token number">8</span>                  <span class="token comment">// String here lock class</span>
         <span class="token number">9</span><span class="token operator">:</span> invokevirtual #<span class="token number">7</span>                  <span class="token comment">// Method java/io/PrintStream.println:(Ljava/lang/String;)V</span>
        <span class="token number">12</span><span class="token operator">:</span> aload_1
        <span class="token number">13</span><span class="token operator">:</span> monitorexit
        <span class="token number">14</span><span class="token operator">:</span> <span class="token keyword">goto</span>          <span class="token number">22</span>
        <span class="token number">17</span><span class="token operator">:</span> astore_2
        <span class="token number">18</span><span class="token operator">:</span> aload_1
        <span class="token number">19</span><span class="token operator">:</span> monitorexit
        <span class="token number">20</span><span class="token operator">:</span> aload_2
        <span class="token number">21</span><span class="token operator">:</span> athrow
        <span class="token number">22</span><span class="token operator">:</span> <span class="token keyword">return</span>
      <span class="token class-name">Exception</span> table<span class="token operator">:</span>
         from    <span class="token keyword">to</span>  <span class="token namespace">target</span> type
             <span class="token number">4</span>    <span class="token number">14</span>    <span class="token number">17</span>   any
            <span class="token number">17</span>    <span class="token number">20</span>    <span class="token number">17</span>   any
      <span class="token class-name">LineNumberTable</span><span class="token operator">:</span>
        line <span class="token number">17</span><span class="token operator">:</span> <span class="token number">0</span>
        line <span class="token number">18</span><span class="token operator">:</span> <span class="token number">4</span>
        line <span class="token number">19</span><span class="token operator">:</span> <span class="token number">12</span>
        line <span class="token number">20</span><span class="token operator">:</span> <span class="token number">22</span>
      <span class="token class-name">StackMapTable</span><span class="token operator">:</span> number_of_entries <span class="token operator">=</span> <span class="token number">2</span>
        frame_type <span class="token operator">=</span> <span class="token number">255</span> <span class="token comment">/* full_frame */</span>
          offset_delta <span class="token operator">=</span> <span class="token number">17</span>
          locals <span class="token operator">=</span> <span class="token punctuation">[</span> <span class="token keyword">class</span> <span class="token class-name">SynchronizedDemo</span><span class="token punctuation">,</span> <span class="token keyword">class</span> java<span class="token operator">/</span>lang<span class="token operator">/</span><span class="token class-name">Object</span> <span class="token punctuation">]</span>
          stack <span class="token operator">=</span> <span class="token punctuation">[</span> <span class="token keyword">class</span> java<span class="token operator">/</span>lang<span class="token operator">/</span><span class="token class-name">Throwable</span> <span class="token punctuation">]</span>
        frame_type <span class="token operator">=</span> <span class="token number">250</span> <span class="token comment">/* chop */</span>
          offset_delta <span class="token operator">=</span> <span class="token number">4</span>
<span class="token punctuation">&#125;</span>
<span class="token class-name">SourceFile</span><span class="token operator">:</span> <span class="token string">"SynchronizedDemo.java"</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>其中<code>lockMethod</code>中可以看到是通过 <code>ACC_SYNCHRONIZED</code> flag 来标记是被 synchronized 修饰，前面的 ACC 应该是 access 的意思，并且通过 <code>ACC_PUBLIC</code> 也可以看出来他们是同一类访问权限关键字来控制的，而修饰类则是通过<code>3: monitorenter</code>和<code>13: monitorexit</code>来控制并发，这个是原来就知道，后来看了下才知道修饰方法是不一样的，但是在前期都比较诟病是 synchronized 的性能，像 monitor 也是通过操作系统的<code>mutex lock</code>互斥锁来实现的，相对是比较重的锁，于是在 JDK 1.6 之后对 synchronized 做了一系列优化，包括偏向锁，轻量级锁，并且包括像 ConcurrentHashMap 这类并发集合都有在使用 synchronized 关键字配合 cas 来做并发保护，</p>
<p>jdk 对于 synchronized 的优化主要在于多重状态锁的升级，最初会使用偏向锁，当一个线程访问同步块并获取锁时，会在对象头和栈帧中的锁记录里存储锁偏向的线程ID，以后该线程在进入和退出同步块时不需要进行CAS操作来加锁和解锁，只需简单地测试一下对象头的Mark Word里是否存储着指向当前线程的偏向锁。引入偏向锁是为了在无多线程竞争的情况下尽量减少不必要的轻量级锁执行路径，因为轻量级锁的获取及释放依赖多次CAS原子指令，而偏向锁只需要在置换ThreadID的时候依赖一次CAS原子指令（由于一旦出现多线程竞争的情况就必须撤销偏向锁，所以偏向锁的撤销操作的性能损耗必须小于节省下来的CAS原子指令的性能消耗）。<br>而当出现线程尝试进入同步块时发现已有偏向锁，并且是其他线程时，会将锁升级成轻量级锁，并且自旋尝试获取锁，如果自旋成功则表示获取轻量级锁成功，否则将会升级成重量级锁进行阻塞，当然这里具体的还很复杂，说的比较浅薄主体还是想将原先的阻塞互斥锁进行轻量化，区分特殊情况进行加锁。</p>
]]></content>
      <categories>
        <category>Java</category>
      </categories>
      <tags>
        <tag>Java</tag>
        <tag>Synchronized</tag>
        <tag>偏向锁</tag>
        <tag>轻量级锁</tag>
        <tag>重量级锁</tag>
        <tag>自旋</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊 Java 的 equals 和 hashCode 方法</title>
    <url>/2021/01/03/%E8%81%8A%E8%81%8A-Java-%E7%9A%84-equals-%E5%92%8C-hashCode-%E6%96%B9%E6%B3%95/</url>
    <content><![CDATA[<p>Java 中的这个话题也是比较常遇到的，关于这块原先也是比较忽略的，但是仔细想想又有点遗忘了就在这里记一下<br>简单看下代码<br><code>java.lang.Object#equals</code></p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">equals</span><span class="token punctuation">(</span><span class="token class-name">Object</span> obj<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> <span class="token punctuation">(</span><span class="token keyword">this</span> <span class="token operator">==</span> obj<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>对于所有对象的父类，<code>equals</code> 方法其实对比的就是对象的地址，也就是是否是同一个对象，试想如果像 Integer 或者 String 这种，我们没有重写 <code>equals</code>，那其实就等于是在用<code>==</code>，可能就没法达到我们的目的，所以像 String 这种常用的 jdk 类都是默认重写了<br><code>java.lang.String#equals</code></p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">equals</span><span class="token punctuation">(</span><span class="token class-name">Object</span> anObject<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span> <span class="token operator">==</span> anObject<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>anObject <span class="token keyword">instanceof</span> <span class="token class-name">String</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">String</span> anotherString <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">)</span>anObject<span class="token punctuation">;</span>
            <span class="token keyword">int</span> n <span class="token operator">=</span> value<span class="token punctuation">.</span>length<span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>n <span class="token operator">==</span> anotherString<span class="token punctuation">.</span>value<span class="token punctuation">.</span>length<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">char</span> v1<span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token operator">=</span> value<span class="token punctuation">;</span>
                <span class="token keyword">char</span> v2<span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token operator">=</span> anotherString<span class="token punctuation">.</span>value<span class="token punctuation">;</span>
                <span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
                <span class="token keyword">while</span> <span class="token punctuation">(</span>n<span class="token operator">--</span> <span class="token operator">!=</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">if</span> <span class="token punctuation">(</span>v1<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">!=</span> v2<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span>
                        <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
                    i<span class="token operator">++</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
                <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>然后呢就是为啥一些书或者 <code>effective java</code> 中写了 <code>equals</code> 跟 <code>hashCode</code> 要一起重写，这里涉及到当对象作为 <code>HashMap</code> 的 <code>key</code> 的时候<br>首先 <code>HashMap</code> 会使用 <code>hashCode</code> 去判断是否在同一个槽里，然后在通过 <code>equals</code> 去判断是否是同一个 <code>key</code>，是的话就替换，不是的话就链表接下去，如果不重写 <code>hashCode</code> 的话，默认的 <code>object</code> 的<code>hashCode</code> 是 <code>native</code> 方法，根据对象的地址生成的，这样其实对象的值相同的话，因为地址不同，<code>HashMap</code> 也会出现异常，所以需要重写，同时也需要重写 <code>equals</code> 方法，才能确认是同一个 <code>key</code>，而不是落在同一个槽的不同 <code>key</code>.</p>
]]></content>
  </entry>
  <entry>
    <title>聊聊 Java 的类加载机制一</title>
    <url>/2020/11/08/%E8%81%8A%E8%81%8A-Java-%E7%9A%84%E7%B1%BB%E5%8A%A0%E8%BD%BD%E6%9C%BA%E5%88%B6/</url>
    <content><![CDATA[<p>一说到这个主题，想到的应该是双亲委派模型，不过讲的包括但不限于这个，主要内容是参考深入理解 Java 虚拟机书中的介绍，<br>一个类型的生命周期包含了七个阶段，加载，验证，准备，解析，初始化，使用，卸载。</p>
<ul>
<li><h2 id="加载"><a href="#加载" class="headerlink" title="加载"></a>加载</h2></li>
</ul>
<ol>
<li>通过一个类的全限定名来获取定义此类的二进制字节流</li>
<li>将这个字节流代表的静态存储结构转化为方法区的运行时数据结构</li>
<li>在内存中生成了一个代表这个类的 java.lang.Class 对象，作为方法区这个类的各种数据的访问入口</li>
</ol>
<ul>
<li><h2 id="验证"><a href="#验证" class="headerlink" title="验证"></a>验证</h2></li>
</ul>
<ol>
<li>文件格式验证</li>
<li>元数据验证</li>
<li>字节码验证</li>
<li>符号引用验证</li>
</ol>
<ul>
<li><h2 id="准备"><a href="#准备" class="headerlink" title="准备"></a>准备</h2><p>准备阶段是正式为类中定义的变量（即静态变量，被static修饰的变量）分配内存并设置类变量初始值的阶段</p>
</li>
<li><h2 id="解析"><a href="#解析" class="headerlink" title="解析"></a>解析</h2><p>解析阶段是 Java 虚拟机将常量池内的符号引用替换为直接引用的过程</p>
</li>
</ul>
<p>以上<a href="##%E9%93%BE%E6%8E%A5">验证</a>、<a href="##%E5%87%86%E5%A4%87">准备</a>、<a href="##%E8%A7%A3%E6%9E%90">解析</a> 三个阶段又合称为链接阶段，链接阶段要做的是将加载到JVM中的二进制字节流的类数据信息合并到JVM的运行时状态中。</p>
<ul>
<li><h2 id="初始化"><a href="#初始化" class="headerlink" title="初始化"></a>初始化</h2>类的初始化阶段是类加载过程的最后一个步骤，也是除了自定义类加载器之外将主动权交给了应用程序，其实就是执行类构造器<clinit>()方法的过程，<clinit>()并不是我们在 Java 代码中直接编写的方法，它是 Javac编译器的自动生成物，<clinit>()方法是由编译器自动收集类中的所有类变量的复制动作和静态句块(static{}块)中的语句合并产生的，编译器收集的顺序是由语句在原文件中出现的顺序决定的，静态语句块中只能访问定义在静态语句块之前的变量，定义在它之后的变量，在前面的静态语句块可以复制，但是不能访问，同时还要保证父类的执行先于子类，然后保证多线程下的并发问题</li>
</ul>
<p>最终，方法区会存储当前类类信息，包括类的静态变量、类初始化代码（定义静态变量时的赋值语句 和 静态初始化代码块）、实例变量定义、实例初始化代码（定义实例变量时的赋值语句实例代码块和构造方法）和实例方法，还有父类的类信息引用。</p>
]]></content>
      <categories>
        <category>Java</category>
        <category>类加载</category>
      </categories>
  </entry>
  <entry>
    <title>聊聊 Linux 下的 top 命令</title>
    <url>/2021/03/28/%E8%81%8A%E8%81%8A-Linux-%E4%B8%8B%E7%9A%84-top-%E5%91%BD%E4%BB%A4/</url>
    <content><![CDATA[<p>top 命令在日常的 Linux 使用中，特别是做一些服务器的简单状态查看，排查故障都起了比较大的作用，但是由于这个命令看到的东西比较多，一般只会看部分，或者说像我这样就会比较片面地看一些信息，比如默认是进程维度的，可以在启动命令的时候加<code>-H</code>进入线程模式</p>
<pre class="line-numbers language-none"><code class="language-none">-H  :Threads-mode operation
            Instructs top to display individual threads.  Without this command-line option a summation of all threads in each process  is  shown.   Later
            this can be changed with the &#96;H&#39; interactive command.<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>这样就能用在 Java 中去 jstack 中找到对应的线程<br>其实还有比较重要的两个操作，<br>一个是在 top 启动状态下，按<code>c</code>键，这样能把比如说是一个 Java 进程，具体的进程命令显示出来<br>像这样<br>执行前是这样<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/LKn8Bs.png"><br>执行后是这样<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/1xD6VM.png"><br>第二个就是排序了</p>
<pre class="line-numbers language-none"><code class="language-none">SORTING of task window

          For  compatibility,  this top supports most of the former top sort keys.  Since this is primarily a service to former top users, these commands
          do not appear on any help screen.
                command   sorted-field                  supported
                A         start time (non-display)      No
                M         %MEM                          Yes
                N         PID                           Yes
                P         %CPU                          Yes
                T         TIME+                         Yes

          Before using any of the following sort provisions, top suggests that you temporarily turn on column highlighting using the &#96;x&#39; interactive com‐
          mand.  That will help ensure that the actual sort environment matches your intent.

          The following interactive commands will only be honored when the current sort field is visible.  The sort field might not be visible because:
                1) there is insufficient Screen Width
                2) the &#96;f&#39; interactive command turned it Off

             &lt;  :Move-Sort-Field-Left
                 Moves the sort column to the left unless the current sort field is the first field being displayed.

             &gt;  :Move-Sort-Field-Right
                 Moves the sort column to the right unless the current sort field is the last field being displayed.<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>查看 man page 可以找到这一段，其实一般 man page 都是最细致的，只不过因为太多了，有时候懒得看，这里可以通过大写 <code>M</code> 和大写 <code>P</code> 分别按内存和 CPU 排序，下面还有两个小技巧，通过按 x 可以将当前活跃的排序列用不同颜色标出来，然后可以通过<code>&lt;</code>和<code>&gt;</code>直接左右移动排序列</p>
]]></content>
      <categories>
        <category>Linux</category>
        <category>小技巧</category>
        <category>命令</category>
        <category>top</category>
        <category>top</category>
        <category>排序</category>
      </categories>
      <tags>
        <tag>排序</tag>
        <tag>linux</tag>
        <tag>小技巧</tag>
        <tag>top</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊 Sharding-Jdbc 分库分表下的分页方案</title>
    <url>/2022/01/09/%E8%81%8A%E8%81%8A-Sharding-Jdbc-%E5%88%86%E5%BA%93%E5%88%86%E8%A1%A8%E4%B8%8B%E7%9A%84%E5%88%86%E9%A1%B5%E6%96%B9%E6%A1%88/</url>
    <content><![CDATA[<p>前面在聊 Sharding-Jdbc 的时候看到了一篇文章，关于一个分页的查询，一直比较直接的想法就是分库分表下的分页是非常不合理的，一般我们的实操方案都是分表加上 ES 搜索做分页，或者通过合表读写分离的方案，因为对于 sharding-jdbc 如果没有带分表键，查询基本都是只能在所有分表都执行一遍，然后再加上分页，基本上是分页越大后续的查询越耗资源，但是仔细的去想这个细节还是这次，就简单说说<br>首先就是我的分表结构</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">CREATE</span> <span class="token keyword">TABLE</span> <span class="token punctuation">`</span>student_time_0<span class="token punctuation">`</span> <span class="token punctuation">(</span>
  <span class="token punctuation">`</span>id<span class="token punctuation">`</span> <span class="token keyword">int</span><span class="token punctuation">(</span><span class="token number">11</span><span class="token punctuation">)</span> <span class="token keyword">unsigned</span> <span class="token operator">NOT</span> <span class="token boolean">NULL</span> <span class="token keyword">AUTO_INCREMENT</span><span class="token punctuation">,</span>
  <span class="token punctuation">`</span>user_id<span class="token punctuation">`</span> <span class="token keyword">int</span><span class="token punctuation">(</span><span class="token number">11</span><span class="token punctuation">)</span> <span class="token operator">NOT</span> <span class="token boolean">NULL</span><span class="token punctuation">,</span>
  <span class="token punctuation">`</span>name<span class="token punctuation">`</span> <span class="token keyword">varchar</span><span class="token punctuation">(</span><span class="token number">200</span><span class="token punctuation">)</span> <span class="token keyword">COLLATE</span> utf8_bin <span class="token keyword">DEFAULT</span> <span class="token boolean">NULL</span><span class="token punctuation">,</span>
  <span class="token punctuation">`</span>age<span class="token punctuation">`</span> <span class="token keyword">tinyint</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span> <span class="token keyword">unsigned</span> <span class="token keyword">DEFAULT</span> <span class="token boolean">NULL</span><span class="token punctuation">,</span>
  <span class="token punctuation">`</span>create_time<span class="token punctuation">`</span> <span class="token keyword">bigint</span><span class="token punctuation">(</span><span class="token number">20</span><span class="token punctuation">)</span> <span class="token keyword">DEFAULT</span> <span class="token boolean">NULL</span><span class="token punctuation">,</span>
  <span class="token keyword">PRIMARY</span> <span class="token keyword">KEY</span> <span class="token punctuation">(</span><span class="token punctuation">`</span>id<span class="token punctuation">`</span><span class="token punctuation">)</span>
<span class="token punctuation">)</span> <span class="token keyword">ENGINE</span><span class="token operator">=</span><span class="token keyword">InnoDB</span> <span class="token keyword">AUTO_INCREMENT</span><span class="token operator">=</span><span class="token number">674</span> <span class="token keyword">DEFAULT</span> <span class="token keyword">CHARSET</span><span class="token operator">=</span>utf8 <span class="token keyword">COLLATE</span><span class="token operator">=</span>utf8_bin<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>有这样的三个表，<code>student_time_0</code>, <code>student_time_1</code>, <code>student_time_2</code>, 以 user_id 作为分表键，根据表数量取模作为分表依据<br>这里先构造点数据，</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">insert</span> <span class="token keyword">into</span> student_time <span class="token punctuation">(</span><span class="token punctuation">`</span>name<span class="token punctuation">`</span><span class="token punctuation">,</span> <span class="token punctuation">`</span>user_id<span class="token punctuation">`</span><span class="token punctuation">,</span> <span class="token punctuation">`</span>age<span class="token punctuation">`</span><span class="token punctuation">,</span> <span class="token punctuation">`</span>create_time<span class="token punctuation">`</span><span class="token punctuation">)</span> <span class="token keyword">values</span> <span class="token punctuation">(</span>?<span class="token punctuation">,</span> ?<span class="token punctuation">,</span> ?<span class="token punctuation">,</span> ?<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>主要是为了保证 <code>create_time</code> 唯一比较好说明问题，</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
<span class="token keyword">try</span> <span class="token punctuation">(</span>
        <span class="token class-name">Connection</span> conn <span class="token operator">=</span> dataSource<span class="token punctuation">.</span><span class="token function">getConnection</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">PreparedStatement</span> ps <span class="token operator">=</span> conn<span class="token punctuation">.</span><span class="token function">prepareStatement</span><span class="token punctuation">(</span>insertSql<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">do</span> <span class="token punctuation">&#123;</span>
        ps<span class="token punctuation">.</span><span class="token function">setString</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> localName <span class="token operator">+</span> <span class="token keyword">new</span> <span class="token class-name">Random</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">nextInt</span><span class="token punctuation">(</span><span class="token number">100</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        ps<span class="token punctuation">.</span><span class="token function">setLong</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">10086L</span> <span class="token operator">+</span> <span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Random</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">nextInt</span><span class="token punctuation">(</span><span class="token number">100</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        ps<span class="token punctuation">.</span><span class="token function">setInt</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">18</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        ps<span class="token punctuation">.</span><span class="token function">setLong</span><span class="token punctuation">(</span><span class="token number">4</span><span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">Date</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getTime</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>


        <span class="token keyword">int</span> result <span class="token operator">=</span> ps<span class="token punctuation">.</span><span class="token function">executeUpdate</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        LOGGER<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"current execute result: &#123;&#125;"</span><span class="token punctuation">,</span> result<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Random</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">nextInt</span><span class="token punctuation">(</span><span class="token number">100</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        i<span class="token operator">++</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span> <span class="token keyword">while</span> <span class="token punctuation">(</span>i <span class="token operator">&lt;=</span> <span class="token number">2000</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>三个表的数据分别是 673，678，650，说明符合预期了，各个表数据不一样，接下来比如我们想要做一个这样的分页查询</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">select</span> <span class="token operator">*</span> <span class="token keyword">from</span> student_time <span class="token keyword">ORDER</span> <span class="token keyword">BY</span> create_time <span class="token keyword">ASC</span> <span class="token keyword">limit</span> <span class="token number">1000</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p><code>student_time</code> 对于我们使用的 <code>sharding-jdbc</code> 来说当然是逻辑表，首先从一无所知去想这个查询如果我们自己来处理应该是怎么做，<br>首先是不是可以每个表都从 333 开始取 5 条数据，类似于下面的查询，然后进行 15 条的合并重排序获取前面的 5 条</p>
<pre class="line-numbers language-none"><code class="language-none">select * from student_time_0 ORDER BY create_time ASC limit 333, 5;
select * from student_time_1 ORDER BY create_time ASC limit 333, 5;
select * from student_time_2 ORDER BY create_time ASC limit 333, 5;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>忽略前面 limit 差的 1，这个结果除非三个表的分布是绝对的均匀，否则结果肯定会出现一定的偏差，以为每个表的 333 这个位置对于其他表来说都不一定是一样的，这样对于最后整体的结果，就会出现偏差<br>因为一直在纠结怎么让这个更直观的表现出来，所以尝试画了个图<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/Gj7TPq.png"><br>黑色的框代表我从每个表里按排序从 334 到 338 的 5 条数据， 他们在每个表里都是代表了各自正确的排序值，但是对于我们想要的其实是合表后的 1001，1005 这五条，然后我们假设总的排序值位于前 1000 的分布是第 0 个表是 320 条，第 1 个表是 340 条，第 2 个表是 340 条，那么可以明显地看出来我这么查的结果简单合并肯定是不对的。<br>那么 sharding-jdbc 是如何保证这个结果的呢，其实就是我在每个表里都查分页偏移量和分页大小那么多的数据，在我这个例子里就是对于 0，1，2 三个分表每个都查 1005 条数据，即使我的数据不平衡到最极端的情况，前 1005 条数据都出在某个分表中，也可以正确获得最后的结果，但是明显的问题就是大分页，数据较多，就会导致非常大的问题，即使如 sharding-jdbc 对于合并排序的优化做得比较好，也还是需要传输那么大量的数据，并且查询也耗时，那么有没有解决方案呢，应该说有两个，或者说主要是想讲后者<br>第一个办法是像这种查询，如果业务上不需要进行跳页，而是只给下一页，那么我们就能把前一次的最大偏移量的 create_time 记录下来，下一页就可以拿着这个偏移量进行查询，这个比较简单易懂，就不多说了<br>第二个办法是看的58 沈剑的一篇文章，尝试理解讲述一下，<br>这个办法的第一步跟前面那个错误的方法或者说不准确的方法一样，先是将分页偏移量平均后在三个表里进行查询</p>
<pre class="line-numbers language-none"><code class="language-none">t0
334 10158 nick95  18  1641548941767
335 10098 nick11  18  1641548941879
336 10167 nick51  18  1641548942089
337 10167 nick3 18  1641548942119
338 10170 nick57  18  1641548942169


t1
334 10105 nick98  18  1641548939071   最小
335 10174 nick94  18  1641548939377
336 10129 nick85  18  1641548939442
337 10141 nick84  18  1641548939480
338 10096 nick74  18  1641548939668

t2
334 10184 nick11  18  1641548945075
335 10109 nick93  18  1641548945382
336 10181 nick41  18  1641548945583
337 10130 nick80  18  1641548945993
338 10184 nick19  18  1641548946294  最大<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>然后要做什么呢，其实目标比较明白，因为前面那种方法其实就是我知道了前一页的偏移量，所以可以直接当做条件来进行查询，那这里我也想着拿到这个条件，所以我将第一遍查出来的最小的 create_time 和最大的 create_time 找出来，然后再去三个表里查询，其实主要是最小值，因为我拿着最小值去查以后我就能知道这个最小值在每个表里处在什么位置，</p>
<pre class="line-numbers language-none"><code class="language-none">t0
322 10161 nick81  18  1641548939284
323 10113 nick16  18  1641548939393
324 10110 nick56  18  1641548939577
325 10116 nick69  18  1641548939588
326 10173 nick51  18  1641548939646

t1
334 10105 nick98  18  1641548939071
335 10174 nick94  18  1641548939377
336 10129 nick85  18  1641548939442
337 10141 nick84  18  1641548939480
338 10096 nick74  18  1641548939668

t2
297 10136 nick28  18  1641548939161
298 10142 nick68  18  1641548939177
299 10124 nick41  18  1641548939237
300 10148 nick87  18  1641548939510
301 10169 nick23  18  1641548939715<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>我只贴了前五条数据，为了方便知道偏移量，每个分表都使用了自增主键，我们可以看到前一次查询的最小值分别在其他两个表里的位置分别是 322-1 和 297-1，那么对于总体来说这个时间应该是在 <code>322 - 1 + 333 + 297 - 1 = 951</code>，那这样子我只要对后面的数据最多每个表查 <code>1000 - 951 + 5 = 54</code> 条数据再进行合并排序就可以获得最终正确的结果。<br>这个就是传说中的二次查询法。</p>
]]></content>
      <categories>
        <category>Java</category>
      </categories>
      <tags>
        <tag>Java</tag>
        <tag>Sharding-Jdbc</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊 Sharding-Jdbc 的简单使用</title>
    <url>/2021/12/12/%E8%81%8A%E8%81%8A-Sharding-Jdbc-%E7%9A%84%E7%AE%80%E5%8D%95%E4%BD%BF%E7%94%A8/</url>
    <content><![CDATA[<p>我们在日常工作中还是使用比较多的分库分表组件的，其中比较优秀的就有 Sharding-Jdbc，一开始由当当开源，后来捐献给了 Apache，说一下简单使用，因为原来经常的使用都是基于 xml 跟 properties 组合起来使用，这里主要试下用 Java Config 来配置<br>首先是通过 Spring Initializr 创建个带 jdbc 的 Spring Boot 项目，然后引入主要的依赖</p>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>dependency</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>groupId</span><span class="token punctuation">></span></span>org.apache.shardingsphere<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>groupId</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>artifactId</span><span class="token punctuation">></span></span>shardingsphere-jdbc-core<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>artifactId</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>version</span><span class="token punctuation">></span></span>5.0.0-beta<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>version</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>dependency</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>因为前面有聊过 Spring Boot 的自动加载，在这里 spring 就会自己去找 DataSource 的配置，所以要在入口把它干掉</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@SpringBootApplication</span><span class="token punctuation">(</span>exclude <span class="token operator">=</span> <span class="token punctuation">&#123;</span> <span class="token class-name">DataSourceAutoConfiguration</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ShardingJdbcDemoApplication</span> <span class="token keyword">implements</span> <span class="token class-name">CommandLineRunner</span> <span class="token punctuation">&#123;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>然后因为想在入口跑代码，就实现了下 <code>org.springframework.boot.CommandLineRunner</code> 主要是后面的 Java Config 代码</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">
<span class="token comment">// 注意这里的注解，可以让 Spring 自动帮忙加载，也就是 Java Config 的核心</span>
<span class="token annotation punctuation">@Configuration</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">MysqlConfig</span> <span class="token punctuation">&#123;</span>

    <span class="token annotation punctuation">@Bean</span>
    <span class="token keyword">public</span> <span class="token class-name">DataSource</span> <span class="token function">dataSource</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">SQLException</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">// Configure actual data sources</span>
        <span class="token class-name">Map</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">DataSource</span><span class="token punctuation">></span></span> dataSourceMap <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">HashMap</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        
        <span class="token comment">// Configure the first data source</span>
        <span class="token comment">// 使用了默认的Hikari连接池的 DataSource</span>
        <span class="token class-name">HikariDataSource</span> dataSource1 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">HikariDataSource</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        dataSource1<span class="token punctuation">.</span><span class="token function">setDriverClassName</span><span class="token punctuation">(</span><span class="token string">"com.mysql.jdbc.Driver"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        dataSource1<span class="token punctuation">.</span><span class="token function">setJdbcUrl</span><span class="token punctuation">(</span><span class="token string">"jdbc:mysql://localhost:3306/sharding"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        dataSource1<span class="token punctuation">.</span><span class="token function">setUsername</span><span class="token punctuation">(</span><span class="token string">"username"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        dataSource1<span class="token punctuation">.</span><span class="token function">setPassword</span><span class="token punctuation">(</span><span class="token string">"password"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        dataSourceMap<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span><span class="token string">"ds0"</span><span class="token punctuation">,</span> dataSource1<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment">// Configure student table rule</span>
        <span class="token comment">// 这里是配置分表逻辑，逻辑表是 student，对应真实的表是 student_0 到 student_1, 这个配置方式就是有多少表可以用 student_$->&#123;0..n&#125;</span>
        <span class="token class-name">ShardingTableRuleConfiguration</span> studentTableRuleConfig <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ShardingTableRuleConfiguration</span><span class="token punctuation">(</span><span class="token string">"student"</span><span class="token punctuation">,</span> <span class="token string">"ds0.student_$->&#123;0..1&#125;"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment">// 设置分表字段</span>
        studentTableRuleConfig<span class="token punctuation">.</span><span class="token function">setTableShardingStrategy</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">StandardShardingStrategyConfiguration</span><span class="token punctuation">(</span><span class="token string">"user_id"</span><span class="token punctuation">,</span> <span class="token string">"tableShardingAlgorithm"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>


        <span class="token comment">// Configure sharding rule</span>
        <span class="token comment">// 配置 studentTableRuleConfig</span>
        <span class="token class-name">ShardingRuleConfiguration</span> shardingRuleConfig <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ShardingRuleConfiguration</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        shardingRuleConfig<span class="token punctuation">.</span><span class="token function">getTables</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>studentTableRuleConfig<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment">// Configure table sharding algorithm</span>
        <span class="token class-name">Properties</span> tableShardingAlgorithmrProps <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Properties</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">// 算法表达式就是根据 user_id 对 2 进行取模</span>
        tableShardingAlgorithmrProps<span class="token punctuation">.</span><span class="token function">setProperty</span><span class="token punctuation">(</span><span class="token string">"algorithm-expression"</span><span class="token punctuation">,</span> <span class="token string">"student_$&#123;user_id % 2&#125;"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        shardingRuleConfig<span class="token punctuation">.</span><span class="token function">getShardingAlgorithms</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span><span class="token string">"tableShardingAlgorithm"</span><span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">ShardingSphereAlgorithmConfiguration</span><span class="token punctuation">(</span><span class="token string">"INLINE"</span><span class="token punctuation">,</span> tableShardingAlgorithmrProps<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>


        <span class="token comment">// 然后创建这个 DataSource</span>
        <span class="token keyword">return</span> <span class="token class-name">ShardingSphereDataSourceFactory</span><span class="token punctuation">.</span><span class="token function">createDataSource</span><span class="token punctuation">(</span>dataSourceMap<span class="token punctuation">,</span> <span class="token class-name">Collections</span><span class="token punctuation">.</span><span class="token function">singleton</span><span class="token punctuation">(</span>shardingRuleConfig<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">Properties</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>然后我们就可以在使用这个 DataSource 了，先看下这两个表的数据<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/LAcX4H.png"><br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/HB4wb1.png"></p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span> args<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        LOGGER<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"run here"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">String</span> sql <span class="token operator">=</span> <span class="token string">"SELECT * FROM student WHERE user_id=? "</span><span class="token punctuation">;</span>
        <span class="token keyword">try</span> <span class="token punctuation">(</span>
                <span class="token class-name">Connection</span> conn <span class="token operator">=</span> dataSource<span class="token punctuation">.</span><span class="token function">getConnection</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token class-name">PreparedStatement</span> ps <span class="token operator">=</span> conn<span class="token punctuation">.</span><span class="token function">prepareStatement</span><span class="token punctuation">(</span>sql<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token comment">// 参数就是 user_id，然后也是分表键，对 2 取模就是 1，应该是去 student_1 取数据</span>
            ps<span class="token punctuation">.</span><span class="token function">setInt</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">1001</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token class-name">ResultSet</span> resultSet <span class="token operator">=</span> ps<span class="token punctuation">.</span><span class="token function">executeQuery</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">while</span> <span class="token punctuation">(</span>resultSet<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">final</span> <span class="token keyword">int</span> id <span class="token operator">=</span> resultSet<span class="token punctuation">.</span><span class="token function">getInt</span><span class="token punctuation">(</span><span class="token string">"id"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">final</span> <span class="token class-name">String</span> name <span class="token operator">=</span> resultSet<span class="token punctuation">.</span><span class="token function">getString</span><span class="token punctuation">(</span><span class="token string">"name"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">final</span> <span class="token keyword">int</span> userId <span class="token operator">=</span> resultSet<span class="token punctuation">.</span><span class="token function">getInt</span><span class="token punctuation">(</span><span class="token string">"user_id"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">final</span> <span class="token keyword">int</span> age <span class="token operator">=</span> resultSet<span class="token punctuation">.</span><span class="token function">getInt</span><span class="token punctuation">(</span><span class="token string">"age"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"奇数表 id："</span> <span class="token operator">+</span> id <span class="token operator">+</span> <span class="token string">" 姓名："</span> <span class="token operator">+</span> name
                        <span class="token operator">+</span> <span class="token string">" 用户 id："</span> <span class="token operator">+</span> userId <span class="token operator">+</span> <span class="token string">" 年龄："</span> <span class="token operator">+</span> age <span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"============================="</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
            <span class="token comment">// 参数就是 user_id，然后也是分表键，对 2 取模就是 0，应该是去 student_0 取数据</span>
            ps<span class="token punctuation">.</span><span class="token function">setInt</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">1000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            resultSet <span class="token operator">=</span> ps<span class="token punctuation">.</span><span class="token function">executeQuery</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">while</span> <span class="token punctuation">(</span>resultSet<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">final</span> <span class="token keyword">int</span> id <span class="token operator">=</span> resultSet<span class="token punctuation">.</span><span class="token function">getInt</span><span class="token punctuation">(</span><span class="token string">"id"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">final</span> <span class="token class-name">String</span> name <span class="token operator">=</span> resultSet<span class="token punctuation">.</span><span class="token function">getString</span><span class="token punctuation">(</span><span class="token string">"name"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">final</span> <span class="token keyword">int</span> userId <span class="token operator">=</span> resultSet<span class="token punctuation">.</span><span class="token function">getInt</span><span class="token punctuation">(</span><span class="token string">"user_id"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">final</span> <span class="token keyword">int</span> age <span class="token operator">=</span> resultSet<span class="token punctuation">.</span><span class="token function">getInt</span><span class="token punctuation">(</span><span class="token string">"age"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"偶数表 id："</span> <span class="token operator">+</span> id <span class="token operator">+</span> <span class="token string">" 姓名："</span> <span class="token operator">+</span> name
                        <span class="token operator">+</span> <span class="token string">" 用户 id："</span> <span class="token operator">+</span> userId <span class="token operator">+</span> <span class="token string">" 年龄："</span> <span class="token operator">+</span> age <span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"============================="</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">SQLException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>看下查询结果<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/hudOBb.png"></p>
]]></content>
      <categories>
        <category>Java</category>
      </categories>
      <tags>
        <tag>Java</tag>
        <tag>Sharding-Jdbc</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊 Sharding-Jdbc 的简单原理初篇</title>
    <url>/2021/12/26/%E8%81%8A%E8%81%8A-Sharding-Jdbc-%E7%9A%84%E7%AE%80%E5%8D%95%E5%8E%9F%E7%90%86%E5%88%9D%E7%AF%87/</url>
    <content><![CDATA[<p>在上一篇 sharding-jdbc 的介绍中其实碰到过一个问题，这里也引出了一个比较有意思的话题<br>就是我在执行 query 的时候犯过一个比较难发现的错误，</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">ResultSet</span> resultSet <span class="token operator">=</span> ps<span class="token punctuation">.</span><span class="token function">executeQuery</span><span class="token punctuation">(</span>sql<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>实际上应该是</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">ResultSet</span> resultSet <span class="token operator">=</span> ps<span class="token punctuation">.</span><span class="token function">executeQuery</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>而这里的差别就是，是否传 sql 这个参数，首先我们要知道这个 ps 是什么，它也是个接口<code>java.sql.PreparedStatement</code>,而真正的实现类是<code>org.apache.shardingsphere.driver.jdbc.core.statement.ShardingSpherePreparedStatement</code>,我们来看下继承关系<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/LqJznh.png"><br>这里可以看到继承关系里有<code>org.apache.shardingsphere.driver.jdbc.unsupported.AbstractUnsupportedOperationPreparedStatement</code><br>那么在我上面的写错的代码里</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Override</span>
<span class="token keyword">public</span> <span class="token keyword">final</span> <span class="token class-name">ResultSet</span> <span class="token function">executeQuery</span><span class="token punctuation">(</span><span class="token keyword">final</span> <span class="token class-name">String</span> sql<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">SQLException</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">SQLFeatureNotSupportedException</span><span class="token punctuation">(</span><span class="token string">"executeQuery with SQL for PreparedStatement"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>这个报错一开始让我有点懵，后来点进去了发现是这么个异常，但是我其实一开始是用的更新语句，以为更新不支持，因为平时使用没有深究过，以为是不是需要使用 Mybatis 才可以执行更新，但是理论上也不应该，再往上看原来这些异常是由 sharding-jdbc 包装的，也就是在上面说的<code>AbstractUnsupportedOperationPreparedStatement</code>，这其实也是一种设计思想，本身 jdbc 提供了一系列接口，由各家去支持，包括 mysql，sql server，oracle 等，而正因为这个设计，所以 sharding-jdbc 也可以在此基础上进行设计，我们可以总体地看下 sharding-jdbc 的实现基础<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/RWvrK6.png"><br>看了前面<code>ShardingSpherePreparedStatement</code>的继承关系，应该也能猜到这里的几个类都是实现了 jdbc 的基础接口，<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/0QncpD.png"><br>在前一篇的 demo 中的</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">Connection</span> conn <span class="token operator">=</span> dataSource<span class="token punctuation">.</span><span class="token function">getConnection</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>其实就获得了<code>org.apache.shardingsphere.driver.jdbc.core.connection.ShardingSphereConnection#ShardingSphereConnection</code><br>然后获得<code>java.sql.PreparedStatement</code></p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">PreparedStatement</span> ps <span class="token operator">=</span> conn<span class="token punctuation">.</span><span class="token function">prepareStatement</span><span class="token punctuation">(</span>sql<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>就是获取了<code>org.apache.shardingsphere.driver.jdbc.core.statement.ShardingSpherePreparedStatement</code><br>然后就是执行</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">ResultSet</span> resultSet <span class="token operator">=</span> ps<span class="token punctuation">.</span><span class="token function">executeQuery</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>然后获得结果<br><code>org.apache.shardingsphere.driver.jdbc.core.resultset.ShardingSphereResultSet</code></p>
<p>其实像 mybatis 也是基于这样去实现的</p>
]]></content>
      <categories>
        <category>Java</category>
      </categories>
      <tags>
        <tag>Java</tag>
        <tag>Sharding-Jdbc</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊 dubbo 的线程池</title>
    <url>/2021/04/04/%E8%81%8A%E8%81%8A-dubbo-%E7%9A%84%E7%BA%BF%E7%A8%8B%E6%B1%A0/</url>
    <content><![CDATA[<p>之前没注意到这一块，只是比较模糊的印象 dubbo 自己基于 ThreadPoolExecutor 定义了几个线程池，但是没具体看过，主要是觉得就是为了避免使用 jdk 自带的那几个(java.util.concurrent.Executors)，防止出现那些问题<br>看下代码目录主要是这几个<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/3qIllK.png"></p>
<ul>
<li>FixedThreadPool：创建一个复用固定个数线程的线程池。<br>简单看下代码<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">Executor</span> <span class="token function">getExecutor</span><span class="token punctuation">(</span><span class="token class-name">URL</span> url<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">String</span> name <span class="token operator">=</span> url<span class="token punctuation">.</span><span class="token function">getParameter</span><span class="token punctuation">(</span><span class="token string">"threadname"</span><span class="token punctuation">,</span> <span class="token string">"Dubbo"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">int</span> threads <span class="token operator">=</span> url<span class="token punctuation">.</span><span class="token function">getParameter</span><span class="token punctuation">(</span><span class="token string">"threads"</span><span class="token punctuation">,</span> <span class="token number">200</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">int</span> queues <span class="token operator">=</span> url<span class="token punctuation">.</span><span class="token function">getParameter</span><span class="token punctuation">(</span><span class="token string">"queues"</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">(</span>threads<span class="token punctuation">,</span> threads<span class="token punctuation">,</span> <span class="token number">0L</span><span class="token punctuation">,</span> <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>MILLISECONDS<span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token class-name">BlockingQueue</span><span class="token punctuation">)</span><span class="token punctuation">(</span>queues <span class="token operator">==</span> <span class="token number">0</span> <span class="token operator">?</span> <span class="token keyword">new</span> <span class="token class-name">SynchronousQueue</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">:</span> <span class="token punctuation">(</span>queues <span class="token operator">&lt;</span> <span class="token number">0</span> <span class="token operator">?</span> <span class="token keyword">new</span> <span class="token class-name">LinkedBlockingQueue</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">:</span> <span class="token keyword">new</span> <span class="token class-name">LinkedBlockingQueue</span><span class="token punctuation">(</span>queues<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">NamedThreadFactory</span><span class="token punctuation">(</span>name<span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">AbortPolicyWithReport</span><span class="token punctuation">(</span>name<span class="token punctuation">,</span> url<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
可以看到核心线程数跟最大线程数一致，也就是说就不会在核心线程数和最大线程数之间动态变化了</li>
<li>LimitedThreadPool：创建一个线程池，这个线程池中线程个数随着需要量动态增加，但是数量不超过配置的阈值的个数，另外空闲线程不会被回收，会一直存在。<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">Executor</span> <span class="token function">getExecutor</span><span class="token punctuation">(</span><span class="token class-name">URL</span> url<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">String</span> name <span class="token operator">=</span> url<span class="token punctuation">.</span><span class="token function">getParameter</span><span class="token punctuation">(</span><span class="token string">"threadname"</span><span class="token punctuation">,</span> <span class="token string">"Dubbo"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">int</span> cores <span class="token operator">=</span> url<span class="token punctuation">.</span><span class="token function">getParameter</span><span class="token punctuation">(</span><span class="token string">"corethreads"</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">int</span> threads <span class="token operator">=</span> url<span class="token punctuation">.</span><span class="token function">getParameter</span><span class="token punctuation">(</span><span class="token string">"threads"</span><span class="token punctuation">,</span> <span class="token number">200</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">int</span> queues <span class="token operator">=</span> url<span class="token punctuation">.</span><span class="token function">getParameter</span><span class="token punctuation">(</span><span class="token string">"queues"</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">(</span>cores<span class="token punctuation">,</span> threads<span class="token punctuation">,</span> <span class="token number">9223372036854775807L</span><span class="token punctuation">,</span> <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>MILLISECONDS<span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token class-name">BlockingQueue</span><span class="token punctuation">)</span><span class="token punctuation">(</span>queues <span class="token operator">==</span> <span class="token number">0</span> <span class="token operator">?</span> <span class="token keyword">new</span> <span class="token class-name">SynchronousQueue</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">:</span> <span class="token punctuation">(</span>queues <span class="token operator">&lt;</span> <span class="token number">0</span> <span class="token operator">?</span> <span class="token keyword">new</span> <span class="token class-name">LinkedBlockingQueue</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">:</span> <span class="token keyword">new</span> <span class="token class-name">LinkedBlockingQueue</span><span class="token punctuation">(</span>queues<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">NamedThreadFactory</span><span class="token punctuation">(</span>name<span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">AbortPolicyWithReport</span><span class="token punctuation">(</span>name<span class="token punctuation">,</span> url<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
这个特点主要是创建了保活时间特别长，即可以认为不会被回收了</li>
<li>EagerThreadPool ：创建一个线程池，这个线程池当所有核心线程都处于忙碌状态时候，创建新的线程来执行新任务，而不是把任务放入线程池阻塞队列。<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">Executor</span> <span class="token function">getExecutor</span><span class="token punctuation">(</span><span class="token class-name">URL</span> url<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">String</span> name <span class="token operator">=</span> url<span class="token punctuation">.</span><span class="token function">getParameter</span><span class="token punctuation">(</span><span class="token string">"threadname"</span><span class="token punctuation">,</span> <span class="token string">"Dubbo"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">int</span> cores <span class="token operator">=</span> url<span class="token punctuation">.</span><span class="token function">getParameter</span><span class="token punctuation">(</span><span class="token string">"corethreads"</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">int</span> threads <span class="token operator">=</span> url<span class="token punctuation">.</span><span class="token function">getParameter</span><span class="token punctuation">(</span><span class="token string">"threads"</span><span class="token punctuation">,</span> <span class="token number">2147483647</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">int</span> queues <span class="token operator">=</span> url<span class="token punctuation">.</span><span class="token function">getParameter</span><span class="token punctuation">(</span><span class="token string">"queues"</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">int</span> alive <span class="token operator">=</span> url<span class="token punctuation">.</span><span class="token function">getParameter</span><span class="token punctuation">(</span><span class="token string">"alive"</span><span class="token punctuation">,</span> <span class="token number">60000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">TaskQueue</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Runnable</span><span class="token punctuation">></span></span> taskQueue <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">TaskQueue</span><span class="token punctuation">(</span>queues <span class="token operator">&lt;=</span> <span class="token number">0</span> <span class="token operator">?</span> <span class="token number">1</span> <span class="token operator">:</span> queues<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">EagerThreadPoolExecutor</span> executor <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">EagerThreadPoolExecutor</span><span class="token punctuation">(</span>cores<span class="token punctuation">,</span> threads<span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token keyword">long</span><span class="token punctuation">)</span>alive<span class="token punctuation">,</span> <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>MILLISECONDS<span class="token punctuation">,</span> taskQueue<span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">NamedThreadFactory</span><span class="token punctuation">(</span>name<span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">AbortPolicyWithReport</span><span class="token punctuation">(</span>name<span class="token punctuation">,</span> url<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        taskQueue<span class="token punctuation">.</span><span class="token function">setExecutor</span><span class="token punctuation">(</span>executor<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> executor<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
这个是改动最多的一个了，因为需要实现这个机制，有兴趣的可以详细看下</li>
<li>CachedThreadPool： 创建一个自适应线程池，当线程处于空闲1分钟时候，线程会被回收，当有新请求到来时候会创建新线程<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">Executor</span> <span class="token function">getExecutor</span><span class="token punctuation">(</span><span class="token class-name">URL</span> url<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">String</span> name <span class="token operator">=</span> url<span class="token punctuation">.</span><span class="token function">getParameter</span><span class="token punctuation">(</span><span class="token string">"threadname"</span><span class="token punctuation">,</span> <span class="token string">"Dubbo"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">int</span> cores <span class="token operator">=</span> url<span class="token punctuation">.</span><span class="token function">getParameter</span><span class="token punctuation">(</span><span class="token string">"corethreads"</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">int</span> threads <span class="token operator">=</span> url<span class="token punctuation">.</span><span class="token function">getParameter</span><span class="token punctuation">(</span><span class="token string">"threads"</span><span class="token punctuation">,</span> <span class="token number">2147483647</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">int</span> queues <span class="token operator">=</span> url<span class="token punctuation">.</span><span class="token function">getParameter</span><span class="token punctuation">(</span><span class="token string">"queues"</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">int</span> alive <span class="token operator">=</span> url<span class="token punctuation">.</span><span class="token function">getParameter</span><span class="token punctuation">(</span><span class="token string">"alive"</span><span class="token punctuation">,</span> <span class="token number">60000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">(</span>cores<span class="token punctuation">,</span> threads<span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token keyword">long</span><span class="token punctuation">)</span>alive<span class="token punctuation">,</span> <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>MILLISECONDS<span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token class-name">BlockingQueue</span><span class="token punctuation">)</span><span class="token punctuation">(</span>queues <span class="token operator">==</span> <span class="token number">0</span> <span class="token operator">?</span> <span class="token keyword">new</span> <span class="token class-name">SynchronousQueue</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">:</span> <span class="token punctuation">(</span>queues <span class="token operator">&lt;</span> <span class="token number">0</span> <span class="token operator">?</span> <span class="token keyword">new</span> <span class="token class-name">LinkedBlockingQueue</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">:</span> <span class="token keyword">new</span> <span class="token class-name">LinkedBlockingQueue</span><span class="token punctuation">(</span>queues<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">NamedThreadFactory</span><span class="token punctuation">(</span>name<span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">AbortPolicyWithReport</span><span class="token punctuation">(</span>name<span class="token punctuation">,</span> url<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
这里可以看到线程池的配置，核心是 0，最大线程数是 2147483647，保活时间是一分钟<br>只是非常简略的介绍下，有兴趣可以自行阅读代码。</li>
</ul>
]]></content>
      <categories>
        <category>Java</category>
        <category>Dubbo - 线程池</category>
        <category>Dubbo</category>
        <category>线程池</category>
        <category>ThreadPool</category>
      </categories>
      <tags>
        <tag>Java</tag>
        <tag>Dubbo</tag>
        <tag>ThreadPool</tag>
        <tag>线程池</tag>
        <tag>FixedThreadPool</tag>
        <tag>LimitedThreadPool</tag>
        <tag>EagerThreadPool</tag>
        <tag>CachedThreadPool</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊 mysql 的 MVCC 续篇</title>
    <url>/2020/05/02/%E8%81%8A%E8%81%8A-mysql-%E7%9A%84-MVCC-%E7%BB%AD%E7%AF%87/</url>
    <content><![CDATA[<p>上一篇聊了mysql 的 innodb 引擎基于 read view 实现的 mvcc 和事务隔离级别，可能有些细心的小伙伴会发现一些问题，第一个是在 RC 级别下的事务提交后的可见性，这里涉及到了三个参数，m_low_limit_id，m_up_limit_id，m_ids，之前看到知乎的一篇写的非常不错的文章，但是就在这一点上似乎有点疑惑，这里基于源码和注释来解释下这个问题</p>
<pre class="line-numbers language-C" data-language="C"><code class="language-C">&#x2F;**
Opens a read view where exactly the transactions serialized before this
point in time are seen in the view.
@param id		Creator transaction id *&#x2F;

void ReadView::prepare(trx_id_t id) &#123;
  ut_ad(mutex_own(&amp;trx_sys-&gt;mutex));

  m_creator_trx_id &#x3D; id;

  m_low_limit_no &#x3D; m_low_limit_id &#x3D; m_up_limit_id &#x3D; trx_sys-&gt;max_trx_id;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>m_low_limit_id赋的值是trx_sys-&gt;max_trx_id，代表的是当前系统最小的未分配的事务 id，所以呢，举个例子，当前有三个活跃事务，事务 id 分别是 100，200，300，而 m_up_limit_id = 100, m_low_limit_id = 301，当事务 id 是 200 的提交之后，它的更新就是可以被 100 和 300 看到，而不是说 m_ids 里没了 200，并且 200 比 100 大就应该不可见了</p>
<h2 id="幻读"><a href="#幻读" class="headerlink" title="幻读"></a>幻读</h2><p>还有一个问题是幻读的问题，这貌似也是个高频面试题，啥意思呢，或者说跟它最常拿来比较的脏读，脏读是指读到了别的事务未提交的数据，因为未提交，严格意义上来讲，不一定是会被最后落到库里，可能会回滚，也就是在 read uncommitted 级别下会出现的问题，但是幻读不太一样，幻读是指两次查询的结果数量不一样，比如我查了第一次是 <code>select * from table1 where id &lt; 10 for update</code>,查出来了一条结果 id 是 5，然后再查一下发现出来了一条 id 是 5，一条 id 是 7，那是不是有点尴尬了，其实呢这个点我觉得脏读跟幻读也比较是从原理层面来命名，如果第一次接触的同学发觉有点不理解也比较正常，因为从逻辑上讲总之都是数据不符合预期，但是基于源码层面其实是不同的情况，幻读是在原先的 read view 无法完全解决的，怎么解决呢，简单的来说就是锁咯，我们知道innodb 是基于 record lock 行锁的，但是貌似没有办法解决这种问题，那么 innodb 就引入了 gap lock 间隙锁，比如上面说的情况下，id 小于 10 的情况下，是都应该锁住的，gap lock 其实是基于索引结构来锁的，因为索引树除了树形结构之外，还有一个next record 的指针，gap lock 也是基于这个来锁的<br>看一下 mysql 的文档</p>
<blockquote>
<p>SELECT … FOR UPDATE sets an exclusive next-key lock on every record the search encounters. However, only an index record lock is required for statements that lock rows using a unique index to search for a unique row.  </p>
</blockquote>
<p>对于一个 for update 查询，在 RR 级别下，会设置一个 next-key lock在每一条被查询到的记录上，next-lock 又是啥呢，其实就是 gap 锁和 record 锁的结合体，比如我在数据库里有 id 是 1，3，5，7，10，对于上面那条查询，查出来的结果就是 1，3，5，7，那么按照文档里描述的，对于这几条记录都会加上next-key lock，也就是(-∞, 1], (1, 3], (3, 5], (5, 7], (7, 10) 这些区间和记录会被锁起来，不让插入，再唠叨一下呢，就是其实如果是只读的事务，光 read view 一致性读就够了，如果是有写操作的呢，就需要锁了。</p>
]]></content>
      <categories>
        <category>Mysql</category>
        <category>C</category>
        <category>数据结构</category>
        <category>源码</category>
        <category>Mysql</category>
      </categories>
      <tags>
        <tag>mysql</tag>
        <tag>数据结构</tag>
        <tag>源码</tag>
        <tag>mvcc</tag>
        <tag>read view</tag>
        <tag>gap lock</tag>
        <tag>next-key lock</tag>
        <tag>幻读</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊 mysql 的 MVCC 续续篇之锁分析</title>
    <url>/2020/05/10/%E8%81%8A%E8%81%8A-mysql-%E7%9A%84-MVCC-%E7%BB%AD%E7%BB%AD%E7%AF%87%E4%B9%8B%E5%8A%A0%E9%94%81%E5%88%86%E6%9E%90/</url>
    <content><![CDATA[<p>看完前面两篇水文之后，感觉不得不来分析下 mysql 的锁了，其实前面说到幻读的时候是有个前提没提到的，比如一个<code>select * from table1 where id  = 1</code>这种查询语句其实是不会加传说中的锁的，当然这里是指在 RR 或者 RC 隔离级别下，<br>看一段 mysql官方文档</p>
<blockquote>
<p><code>SELECT ... FROM</code> is a consistent read, reading a snapshot of the database and setting no locks unless the transaction isolation level is set to SERIALIZABLE. For SERIALIZABLE level, the search sets shared next-key locks on the index records it encounters. However, only an index record lock is required for statements that lock rows using a unique index to search for a unique row.   </p>
</blockquote>
<p>纯粹的这种一致性读，实际读取的是快照，也就是基于 read view 的读取方式，除非当前隔离级别是SERIALIZABLE<br>但是对于以下几类</p>
<ul>
<li><code>select * from table where ? lock in share mode;</code></li>
<li><code>select * from table where ? for update;</code></li>
<li><code>insert into table values (...);</code></li>
<li><code>update table set ? where ?;</code></li>
<li><code>delete from table where ?;</code>  </li>
</ul>
<p>除了第一条是 S 锁之外，其他都是 X 排他锁，这边在顺带下，S 锁表示共享锁， X 表示独占锁，同为 S 锁之间不冲突，S 与 X，X 与 S，X 与 X 之间都冲突，也就是加了前者，后者就加不上了<br>我们知道对于 RC 级别会出现幻读现象，对于 RR 级别不会出现，主要的区别是 RR 级别下对于以上的加锁读取都根据情况加上了 gap 锁，那么是不是 RR 级别下以上所有的都是要加 gap 锁呢，当然不是<br>举个例子，RR 事务隔离级别下，table1 有个主键id 字段<br><code>select * from table1 where id = 10 for update</code><br>这条语句要加 gap 锁吗？<br>答案是不需要，这里其实算是我看了这么久的一点自己的理解，啥时候要加 gap 锁，判断的条件是根据我查询的数据是否会因为不加 gap 锁而出现数量的不一致，我上面这条查询语句，在什么情况下会出现查询结果数量不一致呢，只要在这条记录被更新或者删除的时候，有没有可能我第一次查出来一条，第二次变成两条了呢，不可能，因为是主键索引。<br>再变更下这个题的条件，当 id 不是主键，但是是唯一索引，这样需要怎么加锁，注意问题是怎么加锁，不是需不需要加 gap 锁，这里呢就是稍微延伸一下，把聚簇索引（主键索引）和二级索引带一下，当 id 不是主键，说明是个二级索引，但是它是唯一索引，体会下，首先对于 id = 10这个二级索引肯定要加锁，要不要锁 gap 呢，不用，因为是唯一索引，id = 10 只可能有这一条记录，然后呢，这样是不是就好了，还不行，因为啥，因为它是二级索引，对应的主键索引的记录才是真正的数据，万一被更新掉了咋办，所以在 id = 10 对应的主键索引上也需要加上锁（默认都是 record lock行锁），那主键索引上要不要加 gap 呢，也不用，也是精确定位到这一条记录<br>最后呢，当 id 不是主键，也不是唯一索引，只是个普通的索引，这里就需要大名鼎鼎的 gap 锁了，<br>是时候画个图了<br><img data-src="https://mystore-1255223546.cos.ap-chengdu.myqcloud.com/uPic/WX20200510-1126082x.png"><br>其实核心的目的还是不让这个 id=10 的记录不会出现幻读，那么就需要在 id 这个索引上加上三个 gap 锁，主键索引上就不用了，在 id 索引上已经控制住了id = 10 不会出现幻读，主键索引上这两条对应的记录已经锁了，所以就这样 OK 了</p>
]]></content>
      <categories>
        <category>Mysql</category>
        <category>C</category>
        <category>数据结构</category>
        <category>源码</category>
        <category>Mysql</category>
      </categories>
      <tags>
        <tag>mysql</tag>
        <tag>数据结构</tag>
        <tag>源码</tag>
        <tag>mvcc</tag>
        <tag>read view</tag>
        <tag>gap lock</tag>
        <tag>next-key lock</tag>
        <tag>幻读</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊 mysql 的 MVCC</title>
    <url>/2020/04/26/%E8%81%8A%E8%81%8A-mysql-%E7%9A%84-MVCC/</url>
    <content><![CDATA[<p>很久以前，有位面试官问到，你知道 mysql 的事务隔离级别吗，“额 O__O …，不太清楚”，完了之后我就去网上找相关的文章，找到了这篇<a href="https://www.cnblogs.com/zhoujinyi/p/3437475.html">MySQL 四种事务隔离级的说明</a>, 文章写得特别好，看了这个就懂了各个事务隔离级别都是啥，不过看了这个之后多思考一下的话还是会发现问题，这么神奇的事务隔离级别是怎么实现的呢</p>
<p>其中 innodb 的事务隔离用到了标题里说到的 mvcc，<a href="https://en.wikipedia.org/wiki/Multiversion_concurrency_control"><strong>Multiversion concurrency control</strong></a>, 直译过来就是多版本并发控制，先不讲这个究竟是个啥，考虑下如果纯猜测，这个事务隔离级别应该会是怎么样实现呢，愚钝的我想了下，可以在事务开始的时候拷贝一个表，这个可以支持 RR 级别，RC 级别就不支持了，而且要是个非常大的表，想想就不可行</p>
<p>腆着脸说虽然这个不可行，但是思路是对的，具体实行起来需要做一系列（肥肠多）的改动，首先根据我的理解，其实这个拷贝一个表是变成拷贝一条记录，但是如果有多个事务，那就得拷贝多次，这个问题其实可以借助版本管理系统来解释，在用版本管理系统，git 之类的之前，很原始的可能是开发完一个功能后，就打个压缩包用时间等信息命名，然后如果后面要找回这个就直接用这个压缩包的就行了，后来有了 svn，git 中心式和分布式的版本管理系统，它的一个特点是粒度可以控制到文件和代码行级别，对应的我们的 mysql 事务是不是也可以从一开始预想的表级别细化到行的级别，可能之前很多人都了解过，数据库的一行记录除了我们用户自定义的字段，还有一些额外的字段，去源码<a href="https://github.com/mysql/mysql-server/blob/8.0/storage/innobase/include/data0type.h#L170">data0type.h</a>里捞一下</p>
<pre class="line-numbers language-c" data-language="c"><code class="language-c"><span class="token comment">/* Precise data types for system columns and the length of those columns;
NOTE: the values must run from 0 up in the order given! All codes must
be less than 256 */</span>
<span class="token macro property"><span class="token directive-hash">#</span><span class="token directive keyword">define</span> <span class="token macro-name">DATA_ROW_ID</span> <span class="token expression"><span class="token number">0</span>     </span><span class="token comment">/* row id: a 48-bit integer */</span></span>
<span class="token macro property"><span class="token directive-hash">#</span><span class="token directive keyword">define</span> <span class="token macro-name">DATA_ROW_ID_LEN</span> <span class="token expression"><span class="token number">6</span> </span><span class="token comment">/* stored length for row id */</span></span>

<span class="token comment">/** Transaction id: 6 bytes */</span>
constexpr <span class="token class-name">size_t</span> DATA_TRX_ID <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span>

<span class="token comment">/** Transaction ID type size in bytes. */</span>
constexpr <span class="token class-name">size_t</span> DATA_TRX_ID_LEN <span class="token operator">=</span> <span class="token number">6</span><span class="token punctuation">;</span>

<span class="token comment">/** Rollback data pointer: 7 bytes */</span>
constexpr <span class="token class-name">size_t</span> DATA_ROLL_PTR <span class="token operator">=</span> <span class="token number">2</span><span class="token punctuation">;</span>

<span class="token comment">/** Rollback data pointer type size in bytes. */</span>
constexpr <span class="token class-name">size_t</span> DATA_ROLL_PTR_LEN <span class="token operator">=</span> <span class="token number">7</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>一个是 <code>DATA_ROW_ID</code>，这个是在数据没指定主键的时候会生成一个隐藏的，如果用户有指定主键就是主键了</p>
<p>一个是 <code>DATA_TRX_ID</code>，这个表示这条记录的事务 ID</p>
<p>还有一个是 <code>DATA_ROLL_PTR</code> 指向回滚段的指针</p>
<p>指向的回滚段其实就是我们常说的 undo log，这里面的具体结构就是个链表，在 mvcc 里会使用到这个，还有就是这个 <code>DATA_TRX_ID</code>，每条记录都记录了这个事务 ID，表示的是这条记录的当前值是被哪个事务修改的，下面就扯回事务了，我们知道 <code>Read Uncommitted</code>， 其实用不到隔离，直接读取当前值就好了，到了 <code>Read Committed</code> 级别，我们要让事务读取到提交过的值，mysql 使用了一个叫 <code>read view</code> 的玩意，它里面有这些值是我们需要注意的，</p>
<p><code>m_low_limit_id</code>,  这个是 read view 创建时最大的活跃事务 id</p>
<p><code>m_up_limit_id</code>,  这个是 read view 创建时最小的活跃事务 id</p>
<p><code>m_ids</code>, 这个是 read view 创建时所有的活跃事务 id 数组</p>
<p><code>m_creator_trx_id 这个是当前记录的创建事务 id</code></p>
<p>判断事务的可见性主要的逻辑是这样，</p>
<ol>
<li>当记录的事务 <code>id</code> 小于最小活跃事务 id，说明是可见的，</li>
<li>如果记录的事务 <code>id</code> 等于当前事务 id，说明是自己的更改，可见</li>
<li>如果记录的事务 <code>id</code> 大于最大的活跃事务 <code>id</code>, 不可见</li>
<li>如果记录的事务 <code>id</code> 介于 <code>m_low_limit_id</code> 和 <code>m_up_limit_id</code> 之间，则要判断它是否在 <code>m_ids</code> 中，如果在，不可见，如果不在，表示已提交，可见<br>具体的<a href="https://github.com/mysql/mysql-server/blob/8.0/storage/innobase/include/read0types.h#L160">代码</a>捞一下看看<pre class="line-numbers language-C" data-language="C"><code class="language-C">&#x2F;** Check whether the changes by id are visible.
  @param[in]	id	transaction id to check against the view
  @param[in]	name	table name
  @return whether the view sees the modifications of id. *&#x2F;
  bool changes_visible(trx_id_t id, const table_name_t &amp;name) const
      MY_ATTRIBUTE((warn_unused_result)) &#123;
    ut_ad(id &gt; 0);

    if (id &lt; m_up_limit_id || id &#x3D;&#x3D; m_creator_trx_id) &#123;
      return (true);
    &#125;

    check_trx_id_sanity(id, name);

    if (id &gt;&#x3D; m_low_limit_id) &#123;
      return (false);

    &#125; else if (m_ids.empty()) &#123;
      return (true);
    &#125;

    const ids_t::value_type *p &#x3D; m_ids.data();

    return (!std::binary_search(p, p + m_ids.size(), id));
  &#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
剩下来一点是啥呢，就是 <code>Read Committed</code> 和 <code>Repeated Read</code> 也不一样，那前面说的 <code>read view</code> 都能支持吗，又是怎么支持呢，假如这个 <code>read view</code> 是在事务一开始就创建，那好像能支持的只是 RR 事务隔离级别，其实呢，这是通过创建 <code>read view</code>的时机，对于 RR 级别，就是在事务的第一个 <code>select</code> 语句是创建，对于 RC 级别，是在每个 <code>select</code> 语句执行前都是创建一次，那样就可以保证能读到所有已提交的数据</li>
</ol>
]]></content>
      <categories>
        <category>Mysql</category>
        <category>C</category>
        <category>数据结构</category>
        <category>源码</category>
        <category>Mysql</category>
      </categories>
      <tags>
        <tag>mysql</tag>
        <tag>数据结构</tag>
        <tag>源码</tag>
        <tag>mvcc</tag>
        <tag>read view</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊 mysql 索引的一些细节</title>
    <url>/2020/12/27/%E8%81%8A%E8%81%8A-mysql-%E7%B4%A2%E5%BC%95%E7%9A%84%E4%B8%80%E4%BA%9B%E7%BB%86%E8%8A%82/</url>
    <content><![CDATA[<p>前几天同事问了我个 mysql 索引的问题，虽然大概知道，但是还是想来实践下，就是 is null，is not null 这类查询是否能用索引，可能之前有些网上的文章说都是不能用索引，但是其实不是，我们来看个小试验</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">CREATE</span> <span class="token keyword">TABLE</span> <span class="token punctuation">`</span>null_index_t<span class="token punctuation">`</span> <span class="token punctuation">(</span>
  <span class="token punctuation">`</span>id<span class="token punctuation">`</span> <span class="token keyword">int</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span> <span class="token keyword">unsigned</span> <span class="token operator">NOT</span> <span class="token boolean">NULL</span> <span class="token keyword">AUTO_INCREMENT</span><span class="token punctuation">,</span>
  <span class="token punctuation">`</span>null_key<span class="token punctuation">`</span> <span class="token keyword">varchar</span><span class="token punctuation">(</span><span class="token number">255</span><span class="token punctuation">)</span> <span class="token keyword">DEFAULT</span> <span class="token boolean">NULL</span><span class="token punctuation">,</span>
  <span class="token punctuation">`</span>null_key1<span class="token punctuation">`</span> <span class="token keyword">varchar</span><span class="token punctuation">(</span><span class="token number">255</span><span class="token punctuation">)</span> <span class="token keyword">DEFAULT</span> <span class="token boolean">NULL</span><span class="token punctuation">,</span>
  <span class="token punctuation">`</span>null_key2<span class="token punctuation">`</span> <span class="token keyword">varchar</span><span class="token punctuation">(</span><span class="token number">255</span><span class="token punctuation">)</span> <span class="token keyword">DEFAULT</span> <span class="token boolean">NULL</span><span class="token punctuation">,</span>
  <span class="token keyword">PRIMARY</span> <span class="token keyword">KEY</span> <span class="token punctuation">(</span><span class="token punctuation">`</span>id<span class="token punctuation">`</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
  <span class="token keyword">KEY</span> <span class="token punctuation">`</span>idx_1<span class="token punctuation">`</span> <span class="token punctuation">(</span><span class="token punctuation">`</span>null_key<span class="token punctuation">`</span><span class="token punctuation">)</span> <span class="token keyword">USING</span> <span class="token keyword">BTREE</span><span class="token punctuation">,</span>
  <span class="token keyword">KEY</span> <span class="token punctuation">`</span>idx_2<span class="token punctuation">`</span> <span class="token punctuation">(</span><span class="token punctuation">`</span>null_key1<span class="token punctuation">`</span><span class="token punctuation">)</span> <span class="token keyword">USING</span> <span class="token keyword">BTREE</span><span class="token punctuation">,</span>
  <span class="token keyword">KEY</span> <span class="token punctuation">`</span>idx_3<span class="token punctuation">`</span> <span class="token punctuation">(</span><span class="token punctuation">`</span>null_key2<span class="token punctuation">`</span><span class="token punctuation">)</span> <span class="token keyword">USING</span> <span class="token keyword">BTREE</span>
<span class="token punctuation">)</span> <span class="token keyword">ENGINE</span><span class="token operator">=</span><span class="token keyword">InnoDB</span> <span class="token keyword">DEFAULT</span> <span class="token keyword">CHARSET</span><span class="token operator">=</span>utf8mb4<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>用个存储过程来插入数据</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql">
<span class="token keyword">delimiter</span> $	<span class="token comment">#以delimiter来标记用$表示存储过程结束</span>
<span class="token keyword">create</span> <span class="token keyword">procedure</span> nullIndex1<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">begin</span>
<span class="token keyword">declare</span> i <span class="token keyword">int</span><span class="token punctuation">;</span>	
<span class="token keyword">declare</span> j <span class="token keyword">int</span><span class="token punctuation">;</span>	
<span class="token keyword">set</span> i<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">;</span>
<span class="token keyword">set</span> j<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">;</span>
<span class="token keyword">while</span><span class="token punctuation">(</span>i<span class="token operator">&lt;=</span><span class="token number">100</span><span class="token punctuation">)</span> <span class="token keyword">do</span>	
	<span class="token keyword">while</span><span class="token punctuation">(</span>j<span class="token operator">&lt;=</span><span class="token number">100</span><span class="token punctuation">)</span> <span class="token keyword">do</span>	
		<span class="token keyword">IF</span> <span class="token punctuation">(</span>i <span class="token operator">%</span> <span class="token number">3</span> <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token keyword">THEN</span>
	     <span class="token keyword">INSERT</span> <span class="token keyword">INTO</span> null_index_t <span class="token punctuation">(</span> <span class="token punctuation">`</span>null_key<span class="token punctuation">`</span><span class="token punctuation">,</span> <span class="token punctuation">`</span>null_key1<span class="token punctuation">`</span><span class="token punctuation">,</span> <span class="token punctuation">`</span>null_key2<span class="token punctuation">`</span> <span class="token punctuation">)</span> <span class="token keyword">VALUES</span> <span class="token punctuation">(</span><span class="token boolean">null</span> <span class="token punctuation">,</span> <span class="token keyword">LEFT</span><span class="token punctuation">(</span>MD5<span class="token punctuation">(</span>RAND<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">8</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">LEFT</span><span class="token punctuation">(</span>MD5<span class="token punctuation">(</span>RAND<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">8</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">ELSEIF</span> <span class="token punctuation">(</span>i <span class="token operator">%</span> <span class="token number">3</span> <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token keyword">THEN</span>
			 <span class="token keyword">INSERT</span> <span class="token keyword">INTO</span> null_index_t <span class="token punctuation">(</span> <span class="token punctuation">`</span>null_key<span class="token punctuation">`</span><span class="token punctuation">,</span> <span class="token punctuation">`</span>null_key1<span class="token punctuation">`</span><span class="token punctuation">,</span> <span class="token punctuation">`</span>null_key2<span class="token punctuation">`</span> <span class="token punctuation">)</span> <span class="token keyword">VALUES</span> <span class="token punctuation">(</span><span class="token keyword">LEFT</span><span class="token punctuation">(</span>MD5<span class="token punctuation">(</span>RAND<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">8</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token boolean">NULL</span><span class="token punctuation">,</span> <span class="token keyword">LEFT</span><span class="token punctuation">(</span>MD5<span class="token punctuation">(</span>RAND<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">8</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	  <span class="token keyword">ELSE</span>
			 <span class="token keyword">INSERT</span> <span class="token keyword">INTO</span> null_index_t <span class="token punctuation">(</span> <span class="token punctuation">`</span>null_key<span class="token punctuation">`</span><span class="token punctuation">,</span> <span class="token punctuation">`</span>null_key1<span class="token punctuation">`</span><span class="token punctuation">,</span> <span class="token punctuation">`</span>null_key2<span class="token punctuation">`</span> <span class="token punctuation">)</span> <span class="token keyword">VALUES</span> <span class="token punctuation">(</span><span class="token keyword">LEFT</span><span class="token punctuation">(</span>MD5<span class="token punctuation">(</span>RAND<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">8</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">LEFT</span><span class="token punctuation">(</span>MD5<span class="token punctuation">(</span>RAND<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">8</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token boolean">NULL</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">END</span> <span class="token keyword">IF</span><span class="token punctuation">;</span>
		<span class="token keyword">set</span> j<span class="token operator">=</span>j<span class="token operator">+</span><span class="token number">1</span><span class="token punctuation">;</span>
	<span class="token keyword">end</span> <span class="token keyword">while</span><span class="token punctuation">;</span>
	<span class="token keyword">set</span> i<span class="token operator">=</span>i<span class="token operator">+</span><span class="token number">1</span><span class="token punctuation">;</span>
	<span class="token keyword">set</span> j<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">;</span>	
<span class="token keyword">end</span> <span class="token keyword">while</span><span class="token punctuation">;</span>
<span class="token keyword">end</span> 
$
<span class="token keyword">call</span> nullIndex1<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>然后看下我们的 is null 查询</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">EXPLAIN</span> <span class="token keyword">select</span> <span class="token operator">*</span> <span class="token keyword">from</span> null_index_t <span class="token keyword">WHERE</span> null_key <span class="token operator">is</span> <span class="token boolean">null</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/IejArR.png"><br>再来看看另一个</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">EXPLAIN</span> <span class="token keyword">select</span> <span class="token operator">*</span> <span class="token keyword">from</span> null_index_t <span class="token keyword">WHERE</span> null_key <span class="token operator">is</span> <span class="token operator">not</span> <span class="token boolean">null</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/vwttcE.png"><br>从这里能看出来啥呢，可以思考下</p>
<p>从上面可以发现，<code>is null</code>应该是用上了索引了，所以至少不是一刀切不能用，但是看着<code>is not null</code>好像不太行额<br>我们在做一点小改动，把这个表里的数据改成 9100 条是 null，剩下 900 条是有值的，然后再执行下<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/McIoej.png"><br>然后再来看看执行结果</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">EXPLAIN</span> <span class="token keyword">select</span> <span class="token operator">*</span> <span class="token keyword">from</span> null_index_t <span class="token keyword">WHERE</span> null_key <span class="token operator">is</span> <span class="token boolean">null</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/i4ki84.png"></p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">EXPLAIN</span> <span class="token keyword">select</span> <span class="token operator">*</span> <span class="token keyword">from</span> null_index_t <span class="token keyword">WHERE</span> null_key <span class="token operator">is</span> <span class="token operator">not</span> <span class="token boolean">null</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/1HKVQH.png"><br>是不是不一样了，这里再补充下我试验使用的 mysql 是 5.7 的，不保证在其他版本的一致性，<br>其实可以看出随着数据量的变化，mysql 会不会使用索引是会变化的，不是说 is not null 一定会使用，也不是一定不会使用，而是优化器会根据查询成本做个预判，这个预判尽可能会减小查询成本，主要包括回表啥的，但是也不一定完全准确。</p>
]]></content>
      <categories>
        <category>Mysql</category>
        <category>C</category>
        <category>索引</category>
        <category>Mysql</category>
      </categories>
      <tags>
        <tag>mysql</tag>
        <tag>索引</tag>
        <tag>is null</tag>
        <tag>is not null</tag>
        <tag>procedure</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊 redis 缓存的应用问题</title>
    <url>/2021/01/31/%E8%81%8A%E8%81%8A-redis-%E7%BC%93%E5%AD%98%E7%9A%84%E5%BA%94%E7%94%A8%E9%97%AE%E9%A2%98/</url>
    <content><![CDATA[<p>前面写过一系列的 redis 源码分析的，但是实际上很多的问题还是需要结合实际的使用，然后其实就避不开缓存使用的三个著名问题，穿透，击穿和雪崩，这三个概念也是有着千丝万缕的关系，</p>
<h3 id="缓存穿透"><a href="#缓存穿透" class="headerlink" title="缓存穿透"></a>缓存穿透</h3><p>缓存穿透是指当数据库中本身就不存在这个数据的时候，使用一般的缓存策略时访问不到缓存后就访问数据库，但是因为数据库也没数据，所以如果不做任何策略优化的话，这类数据就每次都会访问一次数据库，对数据库压力也会比较大。</p>
<h3 id="缓存击穿"><a href="#缓存击穿" class="headerlink" title="缓存击穿"></a>缓存击穿</h3><p>缓存击穿跟穿透比较类似的，都是访问缓存不在，然后去访问数据库，与穿透不一样的是击穿是在数据库中存在数据，但是可能由于第一次访问，或者缓存过期了，需要访问到数据库，这对于访问量小的情况其实算是个正常情况，但是随着请求量变高就会引发一些性能隐患。</p>
<h3 id="缓存雪崩"><a href="#缓存雪崩" class="headerlink" title="缓存雪崩"></a>缓存雪崩</h3><p>缓存雪崩就是击穿的大规模集群效应，当大量的缓存过期失效的时候，这些请求都是直接访问到数据库了，会对数据库造成很大的压力。</p>
<p>对于以上三种场景也有一些比较常见的解决方案，但也不能说是万无一失的，需要随着业务去寻找合适的方案</p>
<h3 id="解决缓存穿透"><a href="#解决缓存穿透" class="headerlink" title="解决缓存穿透"></a>解决缓存穿透</h3><p>对于数据库中就没这个数据的时候，一种是可以对这个 key 设置下空值，即以一个特定的表示是数据库不存在的，这种情况需要合理地调整过期时间，当这个 key 在数据库中有数据了的话，也需要有策略去更新这个值，并且如果这类 key 非常多，这个方法就会不太合适，就可以使用第二种方法，就是布隆过滤器，bloom filter，前置一个布隆过滤器，当这个 key 在数据库不存在的话，先用布隆过滤器挡一道，如果不在的话就直接返回了，当然布隆过滤器不是绝对的准确的</p>
<h3 id="解决缓存击穿"><a href="#解决缓存击穿" class="headerlink" title="解决缓存击穿"></a>解决缓存击穿</h3><p>当一个 key 的缓存过期了，如果大量请求过来访问这个 key，请求都会落在数据库里，这个时候就可以使用一些类似于互斥锁的方式去让一个线程去访问数据库，更新缓存，但是这里其实也有个问题，就是如果是热点 key 其实这种方式也比较危险，万一更新失败，或者更新操作的时候耗时比较久，就会有一大堆请求卡在那，这种情况可能需要有一些异步提前刷新缓存，可以结合具体场景选择方式</p>
<h3 id="解决缓存雪崩"><a href="#解决缓存雪崩" class="headerlink" title="解决缓存雪崩"></a>解决缓存雪崩</h3><p>雪崩的情况是指大批量的 key 都一起过期了，击穿的放大版，大批量的请求都打到数据库上了，一方面有可能直接缓存不可用了，就需要用集群化高可用的缓存服务，然后对于实际使用中也可以使用本地缓存结合 redis 缓存，去提高可用性，再配合一些限流措施，然后就是缓存使用过程总的过期时间最好能加一些随机值，防止在同一时间过期而导致雪崩，结合互斥锁防止大量请求打到数据库。</p>
]]></content>
      <categories>
        <category>Redis</category>
        <category>应用</category>
        <category>缓存</category>
        <category>缓存</category>
        <category>穿透</category>
        <category>击穿</category>
        <category>雪崩</category>
      </categories>
      <tags>
        <tag>Redis</tag>
        <tag>缓存穿透</tag>
        <tag>缓存击穿</tag>
        <tag>缓存雪崩</tag>
        <tag>布隆过滤器</tag>
        <tag>bloom filter</tag>
        <tag>互斥锁</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊Java中的单例模式</title>
    <url>/2019/12/21/%E8%81%8A%E8%81%8AJava%E4%B8%AD%E7%9A%84%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F/</url>
    <content><![CDATA[<p>这是个 Java 面试的高频问题，我也遇到过，以往都是觉得这类题没意思，网上一搜一大堆，也不愿意记，其实说回来，主要还是没静下心来好好去理解，今天无意中看到一个课程，基本帮我把一些疑惑的点讲清楚了，首先单例是啥意思，这个其实是有范围一说，比如我起了个<code>Spring Boot</code>应用，在这个应用范围内，我的常规 bean 是单例的，意味着 getBean 的时候其实永远只会拿到那一个对象，那要怎么来写一个单例呢，首先就是传说中的饿汉模式，也是最简单的</p>
<h2 id="饿汉模式"><a href="#饿汉模式" class="headerlink" title="饿汉模式"></a>饿汉模式</h2><pre class="line-numbers language-Java" data-language="Java"><code class="language-Java">public class Singleton1 &#123;
    &#x2F;&#x2F; 首先，将构造方法变成私有的
    private Singleton1() &#123;&#125;;
    &#x2F;&#x2F; 创建私有静态实例，这样第一次使用的时候就会进行创建
    private static Singleton instance &#x3D; new Singleton1();

    &#x2F;&#x2F; 使用这个对象都是通过这个 getInstance 来获取
    public static Singleton1 getInstance() &#123;
        return instance;
    &#125;
    &#x2F;&#x2F; 瞎写一个静态方法。这里想说的是，如果我们只是要调用 Singleton.getDate(...)，
    &#x2F;&#x2F; 本来是不想要生成 Singleton 实例的，不过没办法，已经生成了
    public static Date getDate(String mode) &#123;return new Date();&#125;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>上面借鉴了一些代码，其实这是最基本，也不会错的方法，但是正如其中<code>getDate</code>方法里说的问题，有时候并没有想那这个对象，但是因为我调用了这个类的静态方法，导致对象已经生成了，可能这也是饿汉模式名字的来由，不管三七二十一给你生成个单例就完事了，不管有没有用，但是这种个人觉得也没啥大问题，如果是面试的话最好说出来它的缺点</p>
<h2 id="饱汉模式"><a href="#饱汉模式" class="headerlink" title="饱汉模式"></a>饱汉模式</h2><pre class="line-numbers language-Java" data-language="Java"><code class="language-Java">public class Singleton2 &#123;
    &#x2F;&#x2F; 首先，也是先堵死 new Singleton() 这条路,将构造方法变成私有
    private Singleton2() &#123;&#125;
    &#x2F;&#x2F; 和饿汉模式相比，这边不需要先实例化出来，注意这里的 volatile，它是必须的
    private static volatile Singleton2 instance &#x3D; null;

    private int m &#x3D; 9;

    public static Singleton getInstance() &#123;
        if (instance &#x3D;&#x3D; null) &#123;
            &#x2F;&#x2F; 加锁
            synchronized (Singleton2.class) &#123;
                &#x2F;&#x2F; 这一次判断也是必须的，不然会有并发问题
                if (instance &#x3D;&#x3D; null) &#123;
                    instance &#x3D; new Singleton2();
                &#125;
            &#125;
        &#125;
        return instance;
    &#125;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这里容易错的有三点，理解了其实就比较好记了</p>
<p>第一点，为啥不在 getInstance 上整个代码块加 <code>synchronized</code>，这个其实比较容易理解，就是锁的力度太大，性能太差了，这点其实也要去理解，可以举个夸张的例子，比如我一个电商的服务，如果为了避免一个人的订单出现问题，是不是可以从请求入口就把他锁住，到请求结束释放，那么里面做的事情都有保障，然而这显然不可能，因为我们想要这种竞态条件抢占资源的时间尽量减少，防止其他线程等待。<br>第二点，为啥<code>synchronized</code>之已经检查了 <code>instance == null</code>,还要在里面再检查一次，这个有个术语，叫 <code>double check lock</code>,但是为啥要这么做呢，其实很简单，想象当有两个线程，都过了第一步为空判断，这个时候只有一个线程能拿到这个锁，另一个线程就等待了，如果不再判断一次，那么第一个线程新建完对象释放锁之后，第二个线程又能拿到锁，再去创建一个对象。<br>第三点，为啥要<code>volatile</code>关键字，原先对它的理解是它修饰的变量在 JMM 中能及时将变量值写到主存中，但是它还有个很重要的作用，就是防止指令重排序，<code>instance = new Singleton();</code>这行代码其实在底层是分成三条指令执行的，第一条是在堆上申请了一块内存放这个对象，但是对象的字段啥的都还是默认值，第二条是设置对象的值，比如上面的 m 是 9，然后第三条是将这个对象和虚拟机栈上的指针建立引用关联，那么如果我不用<code>volatile</code>关键字，这三条指令就有可能出现重排，比如变成了 1-3-2 这种顺序，当执行完第二步时，有个线程来访问这个对象了，先判断是不是空，发现不是空的，就拿去直接用了，是不是就出现问题了，所以这个<code>volatile</code>也是不可缺少的</p>
<h2 id="嵌套类"><a href="#嵌套类" class="headerlink" title="嵌套类"></a>嵌套类</h2><pre class="line-numbers language-Java" data-language="Java"><code class="language-Java">public class Singleton3 &#123;

    private Singleton3() &#123;&#125;
    &#x2F;&#x2F; 主要是使用了 嵌套类可以访问外部类的静态属性和静态方法 的特性
    private static class Holder &#123;
        private static Singleton3 instance &#x3D; new Singleton3();
    &#125;
    public static Singleton3 getInstance() &#123;
        return Holder.instance;
    &#125;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这个我个人感觉是饿汉模式的升级版，可以在调用<code>getInstance</code>的时候去实例化对象，也是比较推荐的</p>
<h2 id="枚举单例"><a href="#枚举单例" class="headerlink" title="枚举单例"></a>枚举单例</h2><pre class="line-numbers language-Java" data-language="Java"><code class="language-Java">public enum Singleton &#123;
    INSTANCE;
    
    public void doSomething()&#123;
        &#x2F;&#x2F;todo doSomething
    &#125;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>枚举很特殊，它在类加载的时候会初始化里面的所有的实例，而且 JVM 保证了它们不会再被实例化，所以它天生就是单例的。</p>
]]></content>
      <categories>
        <category>Java</category>
        <category>Design Patterns</category>
        <category>Singleton</category>
      </categories>
      <tags>
        <tag>设计模式</tag>
        <tag>Design Patterns</tag>
        <tag>单例</tag>
        <tag>Singleton</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊一次 brew update 引发的血案</title>
    <url>/2020/06/13/%E8%81%8A%E8%81%8A%E4%B8%80%E6%AC%A1-brew-update-%E5%BC%95%E5%8F%91%E7%9A%84%E8%A1%80%E6%A1%88/</url>
    <content><![CDATA[<p>熟悉我的人（谁熟悉你啊🙄）知道我以前写过 PHP，虽然现在在工作中没用到了，但是自己的一些小工具还是会用 PHP 来写，但是在 Mac 碰到了一个环境相关的问题，因为我也是个更新狂魔，用了 brew 之后因为 gfw 的原因，如果长时间不更新，有时候要装一个用它装一个软件的话，前置的更新耗时就会让人非常头大，所以我基本会隔天 update 一下，但是这样会带来一个很心烦的问题，就是像这样，因为我是要用一个固定版本的 PHP，如果一直升需要一直配扩展啥的也很麻烦，如果一直升级 PHP 到最新版可能会比较少碰到这个问题</p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell">dyld: Library not loaded: &#x2F;usr&#x2F;local&#x2F;opt&#x2F;icu4c&#x2F;lib&#x2F;libicui18n.64.dylib<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>这是什么鬼啊，然后我去这个目录下看了下，已经都是libicui18n.67.dylib了，而且它没有把原来的版本保留下来，首先这个是个叫 icu4c是啥玩意，谷歌了一下</p>
<blockquote>
<p>ICU4C是ICU在C/C++平台下的版本, ICU(International Component for Unicode)是基于”IBM公共许可证”的，与开源组织合作研究的, 用于支持软件国际化的开源项目。ICU4C提供了C/C++平台强大的国际化开发能力，软件开发者几乎可以使用ICU4C解决任何国际化的问题，根据各地的风俗和语言习惯，实现对数字、货币、时间、日期、和消息的格式化、解析，对字符串进行大小写转换、整理、搜索和排序等功能，必须一提的是，ICU4C提供了强大的BIDI算法，对阿拉伯语等BIDI语言提供了完善的支持。</p>
</blockquote>
<p>然后首先想到的解决方案就是能不能我使用<code>brew install icu4c@64</code>来重装下原来的版本，发现不行，并木有，之前的做法就只能是去网上把 64 的下载下来，然后放到这个目录，比较麻烦不智能，虽然没抱着希望在谷歌着，不过这次竟然给我找到了一个我认为非常 nice 的解决方案，因为是在 Stack Overflow 找到的，本着写给像我这样的小小白看的，那就稍微翻译一下<br>第一步，我们到 brew的目录下</p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell">cd $(brew --prefix)&#x2F;Homebrew&#x2F;Library&#x2F;Taps&#x2F;homebrew&#x2F;homebrew-core&#x2F;Formula<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>这个可以理解为是 maven 的 pom 文件，不过有很多不同之处，使用ruby 写的，然后一个文件对应一个组件或者软件，那我们看下有个叫icu4c.rb的文件，<br>第二步看看它的提交历史</p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell">git log --follow icu4c.rb<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>在 git log 的海洋中寻找，寻找它的(64版本)的身影<br><img data-src="https://mystore-1255223546.cos.ap-chengdu.myqcloud.com/uPic/YzS7vN.png"><br>第三步注意这三个红框，Stack Overflow 给出来的答案这一步是找到这个 commit id 直接切出一个新分支</p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell">git checkout -b icu4c-63 e7f0f10dc63b1dc1061d475f1a61d01b70ef2cb7<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>其实注意 commit id 旁边的红框，这个是有tag 的，可以直接</p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell">git checkout icu4c-64<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>PS: 因为我的问题是出在 64 的问题，Stack Overflow 回答的是 63 的，反正是一样的解决方法<br>第四部，切回去之后我们就可以用 brew 提供的基于文件的安装命令来重新装上 64 版本</p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell">brew reinstall .&#x2F;icu4c.rb<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>然后就是第五步，切换版本</p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell">brew switch icu4c 64.2<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>最后把分支切回来</p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell">git checkout master<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>是不是感觉很厉害的解决方法，大佬还提供了一个更牛的，直接写个 zsh 方法</p>
<pre class="line-numbers language-shell" data-language="shell"><code class="language-shell"># zsh
function hiicu64() &#123;
  local last_dir&#x3D;$(pwd)

  cd $(brew --prefix)&#x2F;Homebrew&#x2F;Library&#x2F;Taps&#x2F;homebrew&#x2F;homebrew-core&#x2F;Formula
  git checkout icu4c-4
  brew reinstall .&#x2F;icu4c.rb
  brew switch icu4c 64.2
  git checkout master

  cd $last_dir
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>对应自己的版本改改版本号就可以了，非常好用。</p>
]]></content>
      <categories>
        <category>Mac</category>
        <category>PHP</category>
        <category>Homebrew</category>
        <category>icu4c</category>
      </categories>
      <tags>
        <tag>Mac</tag>
        <tag>PHP</tag>
        <tag>Homebrew</tag>
        <tag>icu4c</tag>
        <tag>zsh</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊传说中的 ThreadLocal</title>
    <url>/2021/05/30/%E8%81%8A%E8%81%8A%E4%BC%A0%E8%AF%B4%E4%B8%AD%E7%9A%84-ThreadLocal/</url>
    <content><![CDATA[<p>说来也惭愧，这个 ThreadLocal 其实一直都是一知半解，而且看了一下之后还发现记错了，所以还是记录下<br>原先记忆里的都是反过来，一个 ThreadLocal 是里面按照 thread 作为 key，存储线程内容的，真的是半解都米有，完全是错的，这样就得用 concurrentHashMap 这种去存储并且要锁定线程了，然后内容也只能存一个了，想想简直智障</p>
<h3 id="究竟是啥结构"><a href="#究竟是啥结构" class="headerlink" title="究竟是啥结构"></a>究竟是啥结构</h3><p>比如我们在代码中 new 一个 ThreadLocal，</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">ThreadLocal</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Man</span><span class="token punctuation">></span></span> tl <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ThreadLocal</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">new</span> <span class="token class-name">Thread</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-></span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>SECONDS<span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>tl<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">new</span> <span class="token class-name">Thread</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-></span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>SECONDS<span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
            tl<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Man</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">static</span> <span class="token keyword">class</span> <span class="token class-name">Man</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">String</span> name <span class="token operator">=</span> <span class="token string">"nick"</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这里构造了两个线程，一个先往里设值，一个后从里取，运行看下结果，<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/uGpXep.png"><br>知道这个用法的话肯定知道是取不到值的，只是具体的原理原来搞错了，我们来看下设值 set 方法</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">set</span><span class="token punctuation">(</span><span class="token class-name">T</span> value<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">Thread</span> t <span class="token operator">=</span> <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">ThreadLocalMap</span> map <span class="token operator">=</span> <span class="token function">getMap</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>map <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span>
        map<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">,</span> value<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">else</span>
        <span class="token function">createMap</span><span class="token punctuation">(</span>t<span class="token punctuation">,</span> value<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>写博客这会我才明白我原来咋会错得这么离谱，看到第一行代码 t 就是当前线程，然后第二行就是用这个线程去<code>getMap</code>，然后我是把这个当成从 map 里取值了，其实这里是</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">ThreadLocalMap</span> <span class="token function">getMap</span><span class="token punctuation">(</span><span class="token class-name">Thread</span> t<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">return</span> t<span class="token punctuation">.</span>threadLocals<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>获取 t 的 threadLocals 成员变量，那这个 threadLocals 又是啥呢<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/4p5MdM.png"><br>它其实是线程 Thread 中的一个类型是java.lang.ThreadLocal.ThreadLocalMap的成员变量<br>这是 ThreadLocal 的一个静态成员变量</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">static</span> <span class="token keyword">class</span> <span class="token class-name">ThreadLocalMap</span> <span class="token punctuation">&#123;</span>

        <span class="token comment">/**
         * The entries in this hash map extend WeakReference, using
         * its main ref field as the key (which is always a
         * ThreadLocal object).  Note that null keys (i.e. entry.get()
         * == null) mean that the key is no longer referenced, so the
         * entry can be expunged from table.  Such entries are referred to
         * as "stale entries" in the code that follows.
         */</span>
        <span class="token keyword">static</span> <span class="token keyword">class</span> <span class="token class-name">Entry</span> <span class="token keyword">extends</span> <span class="token class-name">WeakReference</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">ThreadLocal</span><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span><span class="token punctuation">></span></span> <span class="token punctuation">&#123;</span>
            <span class="token comment">/** The value associated with this ThreadLocal. */</span>
            <span class="token class-name">Object</span> value<span class="token punctuation">;</span>

            <span class="token class-name">Entry</span><span class="token punctuation">(</span><span class="token class-name">ThreadLocal</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span> k<span class="token punctuation">,</span> <span class="token class-name">Object</span> v<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">super</span><span class="token punctuation">(</span>k<span class="token punctuation">)</span><span class="token punctuation">;</span>
                value <span class="token operator">=</span> v<span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>全部代码有点长，只截取了一小部分，然后我们再回头来分析前面说的 set 过程，再 copy 下代码</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">set</span><span class="token punctuation">(</span><span class="token class-name">T</span> value<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">Thread</span> t <span class="token operator">=</span> <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">ThreadLocalMap</span> map <span class="token operator">=</span> <span class="token function">getMap</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>map <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span>
        map<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">,</span> value<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">else</span>
        <span class="token function">createMap</span><span class="token punctuation">(</span>t<span class="token punctuation">,</span> value<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>获取到 map 以后呢，如果 map 不为空，就往 map 里 set，这里注意 key 是啥，其实是当前这个 ThreadLocal，这里就比较明白了究竟是啥结构，每个线程都会维护自身的 ThreadLocalMap，它是线程的一个成员变量，当创建 ThreadLocal 的时候，进行设值的时候其实是往这个 map 里以 ThreadLocal 作为 key，往里设 value。</p>
<h3 id="内存泄漏是什么鬼"><a href="#内存泄漏是什么鬼" class="headerlink" title="内存泄漏是什么鬼"></a>内存泄漏是什么鬼</h3><p>这里又要看下前面的 ThreadLocalMap 结构了，类似 HashMap，它有个 Entry 结构，在设置的时候会先包装成一个 Entry</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">set</span><span class="token punctuation">(</span><span class="token class-name">ThreadLocal</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span> key<span class="token punctuation">,</span> <span class="token class-name">Object</span> value<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>

        <span class="token comment">// We don't use a fast path as with get() because it is at</span>
        <span class="token comment">// least as common to use set() to create new entries as</span>
        <span class="token comment">// it is to replace existing ones, in which case, a fast</span>
        <span class="token comment">// path would fail more often than not.</span>

        <span class="token class-name">Entry</span><span class="token punctuation">[</span><span class="token punctuation">]</span> tab <span class="token operator">=</span> table<span class="token punctuation">;</span>
        <span class="token keyword">int</span> len <span class="token operator">=</span> tab<span class="token punctuation">.</span>length<span class="token punctuation">;</span>
        <span class="token keyword">int</span> i <span class="token operator">=</span> key<span class="token punctuation">.</span>threadLocalHashCode <span class="token operator">&amp;</span> <span class="token punctuation">(</span>len<span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">Entry</span> e <span class="token operator">=</span> tab<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">;</span>
             e <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
             e <span class="token operator">=</span> tab<span class="token punctuation">[</span>i <span class="token operator">=</span> <span class="token function">nextIndex</span><span class="token punctuation">(</span>i<span class="token punctuation">,</span> len<span class="token punctuation">)</span><span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">ThreadLocal</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span> k <span class="token operator">=</span> e<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token keyword">if</span> <span class="token punctuation">(</span>k <span class="token operator">==</span> key<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                e<span class="token punctuation">.</span>value <span class="token operator">=</span> value<span class="token punctuation">;</span>
                <span class="token keyword">return</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>

            <span class="token keyword">if</span> <span class="token punctuation">(</span>k <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token function">replaceStaleEntry</span><span class="token punctuation">(</span>key<span class="token punctuation">,</span> value<span class="token punctuation">,</span> i<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">return</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>

        tab<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Entry</span><span class="token punctuation">(</span>key<span class="token punctuation">,</span> value<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">int</span> sz <span class="token operator">=</span> <span class="token operator">++</span>size<span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token function">cleanSomeSlots</span><span class="token punctuation">(</span>i<span class="token punctuation">,</span> sz<span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> sz <span class="token operator">>=</span> threshold<span class="token punctuation">)</span>
            <span class="token function">rehash</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这里其实比较重要的就是前面的 Entry 的构造方法，Entry 是个 WeakReference 的子类，然后在构造方法里可以看到 key 会被包装成一个弱引用，这里为什么使用弱引用，其实是方便这个 key 被回收，如果前面的 ThreadLocal  tl实例被设置成 null 了，如果这里是直接的强引用的话，就只能等到线程整个回收了，但是其实是弱引用也会有问题，主要是因为这个 value，如果在 ThreadLocal tl 被设置成 null 了，那么其实这个 value 就会没法被访问到，所以最好的操作还是在使用完了就 remove 掉</p>
]]></content>
      <categories>
        <category>Java</category>
      </categories>
      <tags>
        <tag>Java</tag>
        <tag>ThreadLocal</tag>
        <tag>弱引用</tag>
        <tag>内存泄漏</tag>
        <tag>WeakReference</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊厦门旅游的好与不好</title>
    <url>/2021/04/11/%E8%81%8A%E8%81%8A%E5%8E%A6%E9%97%A8%E6%97%85%E6%B8%B8%E7%9A%84%E5%A5%BD%E4%B8%8E%E4%B8%8D%E5%A5%BD/</url>
    <content><![CDATA[<p>这几天去了趟厦门，原来几年前就想去了，本来都请好假了，后面因为一些事情没去成，这次刚好公司组织，就跟 LD 一起去了厦门，也不洋洋洒洒地写游记了，后面可能会有，今天先来总结下好的地方和比较坑的地方。<br>这次主要去了中山路、鼓浪屿、曾厝(cuo)垵、植物园、灵玲马戏团，因为住的离环岛路比较近，还有幸现场看了下厦门马拉松，其中</p>
<h2 id="中山路"><a href="#中山路" class="headerlink" title="中山路"></a>中山路</h2><p>这里看上去是有点民国时期的建筑风格，部分像那种电视里的租界啥的，不过这次去的时候都在翻修，路一大半拦起来了，听导游说这里往里面走有个局口街，然后上次听前同事说厦门比较有名的就是沙茶面和海蛎煎，不出意料的不太爱吃，沙茶面比较普通，可能是没吃到正宗的，海蛎煎吃不惯，倒是有个大叔的沙茶里脊还不错，在局口街那，还有小哥在那拍，应该也算是个网红打卡点了，然后吃了个油条麻糍也还不错，总体如果是看建筑的话可能最近不是个好时间，个人也没这方面爱好，吃的话最好多打听打听沙茶面跟海蛎煎哪里正宗。如果不知道哪家好吃，也不爱看这类建筑的可以排个坑。</p>
<h2 id="鼓浪屿"><a href="#鼓浪屿" class="headerlink" title="鼓浪屿"></a>鼓浪屿</h2><p>鼓浪屿也是完全没啥概念，需要乘船过去，但是只要二十分钟，岛上没有机动车，基本都靠走，有几个比较有名的地方，菽庄花园，里面有钢琴博物馆，对这个感兴趣的可以去看看，旁边是沙滩还可以逛逛，然后有各种博物馆，风琴啥的，岛上最大的特色是巷子多，道听途说有三百多条小巷，还有几个网红打卡点，周杰伦晴天墙，还有个最美转角，都是挤满了人排队打卡拍照，不过如果不着急，慢慢悠悠逛逛还是不错的，比较推荐，推荐值☆☆</p>
<h2 id="曾厝垵"><a href="#曾厝垵" class="headerlink" title="曾厝垵"></a>曾厝垵</h2><p>一直读不对这个字，都是叫：那个曾什么垵，愧对语文老师，这里到算是意外之喜，鼓浪屿回来已经挺累了，不过由于比较饿（什么原因后面说），并且离住的地方不远，就过去逛了逛，东西还蛮好吃的，芒果挺便宜，一大杯才十块，无骨鸡爪很贵，不是特别爱，臭豆腐不错的，也不算很贵，这里想起来，那边八婆婆的豆乳烧仙草还不错的，去中山路那会喝了，来曾厝垵也买了，奶茶爱好者可以试试，含糖量应该很高，不爱甜食或者减肥的同学慎重考虑好了再尝试，晚上那边从牌坊出来，沿着环岛路挺多夜宵店什么的，非常推荐，推荐值☆☆☆☆</p>
<h2 id="植物园"><a href="#植物园" class="headerlink" title="植物园"></a>植物园</h2><p>植物园还是挺名副其实的，有热带植物，沙漠多肉，因为赶时间逛得不多，热带雨林植物那太多人了，都是在那拍照，而且我指的拍照都是拍人照，本身就很小的路，各种十八线网红，或者普通游客在那摆 pose 拍照，挺无语的；沙漠多肉比较惊喜，好多比人高的仙人掌，一大片的仙人球，很可恶的是好多大仙人掌上都有人刻字，越来越体会到，我们社会人多了，什么样的都有，而且不少；还看了下百花厅，但没什么特别的，可能赶时间比较着急，没仔细看，比较推荐，推荐值☆☆☆</p>
<h2 id="灵玲马戏团"><a href="#灵玲马戏团" class="headerlink" title="灵玲马戏团"></a>灵玲马戏团</h2><p>对这个其实比较排斥，主要是比较晚了，跑的有点远（我太懒了），一开始真的挺拉低体验感受的，上来个什么书法家，现场画马，卖画；不过后面的还算值回票价，主题是花木兰，空中动作应该很考验基本功，然后那些老外的飞轮还跳绳（不知道学名叫啥），动物那块不太忍心看，应该是吃了不少苦头，不过人都这样就往后点再心疼动物吧。</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>厦门是个非常适合干饭人的地方，吃饭的地方大部分是差不多一桌菜十个左右就完了，而且上来就一大碗饭，一瓶雪碧一瓶可乐，对于经常是家里跟亲戚吃饭都得十几二十个菜的乡下人来说，不太吃得惯这样的🤦‍♂️，当然很有可能是我们预算不足，点的差。但是有一点是我回杭州深有感触的，感觉杭州司机的素质真的是跟厦门的司机差了比较多，杭州除非公交车停了，否则人行道很难看到主动让人的，当然这里拿厦门这个旅游城市来对比也不是很公平，不过这也是体现城市现代化文明水平的一个维度吧。</p>
]]></content>
      <categories>
        <category>生活</category>
        <category>旅游</category>
      </categories>
      <tags>
        <tag>生活</tag>
        <tag>杭州</tag>
        <tag>旅游</tag>
        <tag>厦门</tag>
        <tag>中山路</tag>
        <tag>局口街</tag>
        <tag>鼓浪屿</tag>
        <tag>曾厝垵</tag>
        <tag>植物园</tag>
        <tag>马戏团</tag>
        <tag>沙茶面</tag>
        <tag>海蛎煎</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊如何识别和意识到日常生活中的各类危险</title>
    <url>/2021/06/06/%E8%81%8A%E8%81%8A%E5%A6%82%E4%BD%95%E8%AF%86%E5%88%AB%E5%92%8C%E6%84%8F%E8%AF%86%E5%88%B0%E6%97%A5%E5%B8%B8%E7%94%9F%E6%B4%BB%E4%B8%AD%E7%9A%84%E5%90%84%E7%B1%BB%E5%8D%B1%E9%99%A9/</url>
    <content><![CDATA[<p>这篇博客的灵感又是来自于我从绍兴来杭州的路上，在我们进站以后上电梯快到的时候，突然前面不动了，右边我能看到的是有个人的行李箱一时拎不起来，另一边后面看到其实是个小孩子在那哭闹，一位妈妈就在那停着安抚或者可能有点手足无措，其实这一点应该是在几年前慢慢意识到是个非常危险的场景，特别是像绍兴北站这样上去站台是非常长的电梯，因为最近扩建改造，车次减少了很多，所以每一班都有很多人，检票上站台的电梯都是满员运转，试想这种情况，如果刚才那位妈妈再多停留一点时间，很可能就会出现后面的人上不来被挤下去，再严重点就是踩踏事件，但是这类情况很少人真的意识到，非常明显的例子就是很多人拿着比较大比较重的行李箱，不走垂梯，并且在快到的时候没有提前准备好，有可能在玩手机啥的，如果提不动，后面又是挤满人了，就很可能出现前面说的这种情况，并且其实这种是非紧急情况，大多数人都没有心理准备，一旦发生后果可能就会很严重，例如火灾地震疏散大部分人或者说负责引导的都是指示要有序撤离，防止踩踏，但是普通坐个扶梯，一般都不会有这个意识，但是如果这个时间比较长，出现了人员站不住往后倒了，真的会很严重。所以如果自己是带娃的或者带了很重的行李箱的，请提前做好准备，看到前面有人带的，最好也保持一定距离。<br>还有比如日常走路，旁边有车子停着的情况，比较基本的看车灯有没有亮着，亮着的是否是倒车灯，这种应该特别注意远离，至少保持距离，不能挨着走，很多人特别是一些老年人，在一些人比较多的路上，往往完全无视旁边这些车的状态，我走我的路，谁敢阻拦我，管他车在那动不动，其实真的非常危险，车子本身有视线死角，再加上司机的驾驶习惯和状态，想去送死跟碰瓷的除外，还有就是有一些车会比较特殊，车子发动着，但是没灯，可能是车子灯坏了或者司机通过什么方式关了灯，这种比较难避开，不过如果车子打着了，一般会有比较大的热量散发，车子刚灭了也会有，反正能远离点尽量远离，从轿车的车前面走过挨着走要比从屁股后面挨着走稍微安全一些，但也最好不要挨着车走。<br>最后一点其实是我觉得是我自己比较怕死，一般对来向的车或者从侧面出来的车会做更长的预判距离，特别是电瓶车，一般是不让人的，像送外卖的小哥，的确他们不太容易，但是真的很危险啊，基本就生死看刹车，能刹住就赚了，刹不住就看身子骨扛不扛撞了，只是这里要多说点又要谈到资本的趋利性了，总是想法设法的压榨以获取更多的利益，也不扯远了，能远离就远离吧。</p>
]]></content>
      <categories>
        <category>生活</category>
      </categories>
      <tags>
        <tag>生活</tag>
        <tag>糟心事</tag>
        <tag>扶梯</tag>
        <tag>踩踏</tag>
        <tag>安全</tag>
        <tag>电瓶车</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊我刚学会的应用诊断方法</title>
    <url>/2020/05/22/%E8%81%8A%E8%81%8A%E6%88%91%E5%88%9A%E5%AD%A6%E4%BC%9A%E7%9A%84%E5%BA%94%E7%94%A8%E8%AF%8A%E6%96%AD%E6%96%B9%E6%B3%95/</url>
    <content><![CDATA[<p>因为传说中的出身问题，我以前写的是PHP，在使用 swoole 之前，基本的应用调试手段就是简单粗暴的 var_dump，exit，对于单进程模型的 PHP 也是简单有效，技术栈换成 Java 之后，就变得没那么容易，一方面是需要编译，另一方面是一般都是基于 spring 的项目，如果问题定位比较模糊，那框架层的是很难靠简单的 System.out.println 或者打 log 解决，(PS：我觉得可能我写的东西比较适合从 PHP 这种弱类型语言转到 Java 的小白同学)这个时候一方面因为是 Java，有了非常好用的 idea IDE 的支持，可以各种花式调试，条件断点尤其牛叉，但是又因为有 Spring+Java 的双重原因，有些情况下单步调试可以把手按废掉，这也是我之前一直比较困惑苦逼的点，后来随着慢慢精（jiang）进（you）之后，比如对于一个 oom 的情况，我们可以通过启动参数加上-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=xx/xx 来配置溢出时的堆dump 日志，获取到这个文件后，我们可以通过像 Memory Analyzer (MAT)[<a href="https://www.eclipse.org/mat/]">https://www.eclipse.org/mat/]</a> (The Eclipse Memory Analyzer is a fast and feature-rich Java heap analyzer that helps you find memory leaks and reduce memory consumption.)来查看诊断问题所在，之前用到的时候是因为有个死循环一直往链表里塞数据，属于比较简单的，后来一次是由于运维进行应用迁移时按默认的统一配置了堆内存大小，导致内存的确不够用，所以溢出了，<br>今天想说的其实主要是我们的 thread dump，这也是我最近才真正用的一个方法，可能真的很小白了，用过 ide 的单步调试其实都知道会有一个一层层的玩意，比如函数从 A，调用了 B，再从 B 调用了 C，一直往下(因为是 Java，所以还有很多🤦‍♂️)，这个其实也是大部分语言的调用模型，利用了栈这个数据结构，通过这个结构我们可以知道代码的调用链路，由于对于一个 spring 应用，在本身框架代码量非常庞大的情况下，外加如果应用代码也是非常多的时候，有时候通过单步调试真的很难短时间定位到问题，需要非常大的耐心和仔细观察，当然不是说完全不行，举个例子当我的应用经常启动需要非常长的时间，因为本身应用有非常多个 bean，比较难说究竟是 bean 的加载的确很慢还是有什么异常原因，这种时候就可以使用 thread dump 了，具体怎么操作呢<br><img data-src="https://mystore-1255223546.cos.ap-chengdu.myqcloud.com/uPic/GPYHjd.png"><br>如果在idea 中运行或者调试时，可以直接点击这个照相机一样的按钮，右边就会出现了左边会显示所有的线程，右边会显示线程栈，</p>
<pre class="line-numbers language-none"><code class="language-none">&quot;main@1&quot; prio&#x3D;5 tid&#x3D;0x1 nid&#x3D;NA runnable
  java.lang.Thread.State: RUNNABLE
	  at TreeDistance.treeDist(TreeDistance.java:64)
	  at TreeDistance.treeDist(TreeDistance.java:65)
	  at TreeDistance.treeDist(TreeDistance.java:65)
	  at TreeDistance.treeDist(TreeDistance.java:65)
	  at TreeDistance.main(TreeDistance.java:45)<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这就是我们主线程的堆栈信息了，main 表示这个线程名，prio表示优先级，默认是 5，tid 表示线程 id，nid 表示对应的系统线程，后面的runnable 表示目前线程状态，因为是被我打了断点，所以是就许状态，然后下面就是对应的线程栈内容了，在<code>TreeDistance</code>类的 <code>treeDist</code>方法中，对应的文件行数是 64 行。<br>这里使用 thread dump一般也不会是上面我截图代码里的这种代码量很少的，一般是大型项目，有时候跑着跑着没反应，又不知道跑到哪了，特别是一些刚接触的大项目或者需要定位一个大项目的一个疑难问题，一时没思路时，可以使用这个方法，个人觉得非常有帮助。</p>
]]></content>
      <categories>
        <category>Java</category>
        <category>Thread dump</category>
        <category>问题排查</category>
        <category>工具</category>
      </categories>
      <tags>
        <tag>Java</tag>
        <tag>Thread dump</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊我理解的分布式事务</title>
    <url>/2020/05/17/%E8%81%8A%E8%81%8A%E6%88%91%E7%90%86%E8%A7%A3%E7%9A%84%E5%88%86%E5%B8%83%E5%BC%8F%E4%BA%8B%E5%8A%A1/</url>
    <content><![CDATA[<p>前面说了mysql数据库的事务相关的，那事务是用来干嘛的，这里得补一下ACID，</p>
<blockquote>
<p><a href="https://zh.wikipedia.org/wiki/ACID"><strong>ACID</strong></a>，是指<a href="https://zh.wikipedia.org/wiki/%E6%95%B0%E6%8D%AE%E5%BA%93%E7%AE%A1%E7%90%86%E7%B3%BB%E7%BB%9F">数据库管理系统</a>（<a href="https://zh.wikipedia.org/wiki/DBMS">DBMS</a>）在写入或更新资料的过程中，为保证<a href="https://zh.wikipedia.org/wiki/%E6%95%B0%E6%8D%AE%E5%BA%93%E4%BA%8B%E5%8A%A1">事务</a>（transaction）是正确可靠的，所必须具备的四个特性：<a href="https://zh.wikipedia.org/w/index.php?title=%E5%8E%9F%E5%AD%90%E6%80%A7&action=edit&redlink=1">原子性</a>（atomicity，或称不可分割性）、<a href="https://zh.wikipedia.org/w/index.php?title=%E4%B8%80%E8%87%B4%E6%80%A7_(%E6%95%B0%E6%8D%AE%E5%BA%93%E7%B3%BB%E7%BB%9F)&action=edit&redlink=1">一致性</a>（consistency）、<a href="https://zh.wikipedia.org/wiki/%E9%9A%94%E9%9B%A2%E6%80%A7">隔离性</a>（isolation，又称独立性）、<a href="https://zh.wikipedia.org/w/index.php?title=%E6%8C%81%E4%B9%85%E6%80%A7&action=edit&redlink=1">持久性</a>（durability）。</p>
</blockquote>
<ul>
<li><p>Atomicity（原子性）：一个事务（transaction）中的所有操作，或者全部完成，或者全部不完成，不会结束在中间某个环节。事务在执行过程中发生错误，会被<a href="https://zh.wikipedia.org/wiki/%E5%9B%9E%E6%BB%9A_(%E6%95%B0%E6%8D%AE%E7%AE%A1%E7%90%86)">回滚</a>（Rollback）到事务开始前的状态，就像这个事务从来没有执行过一样。即，事务不可分割、不可约简。[<a href="https://zh.wikipedia.org/wiki/ACID#cite_note-acid-1">1]</a></p>
</li>
<li><p>Consistency（一致性）：在事务开始之前和事务结束以后，数据库的完整性没有被破坏。这表示写入的资料必须完全符合所有的预设<a href="https://zh.wikipedia.org/wiki/%E6%95%B0%E6%8D%AE%E5%AE%8C%E6%95%B4%E6%80%A7">约束</a>、<a href="https://zh.wikipedia.org/wiki/%E8%A7%A6%E5%8F%91%E5%99%A8_(%E6%95%B0%E6%8D%AE%E5%BA%93)">触发器</a>、<a href="https://zh.wikipedia.org/wiki/%E7%BA%A7%E8%81%94%E5%9B%9E%E6%BB%9A">级联回滚</a>等。[<a href="https://zh.wikipedia.org/wiki/ACID#cite_note-acid-1">1]</a></p>
</li>
<li><p>Isolation（隔离性）：数据库允许多个并发事务同时对其数据进行读写和修改的能力，隔离性可以防止多个事务并发执行时由于交叉执行而导致数据的不一致。事务隔离分为不同级别，包括未提交读（Read uncommitted）、提交读（read committed）、可重复读（repeatable read）和串行化（Serializable）。[<a href="https://zh.wikipedia.org/wiki/ACID#cite_note-acid-1">1]</a></p>
</li>
<li><p>Durability（持久性）：事务处理结束后，对数据的修改就是永久的，即便系统故障也不会丢失。[<a href="https://zh.wikipedia.org/wiki/ACID#cite_note-acid-1">1]</a></p>
</li>
</ul>
<p>在mysql中，借助于MVCC，各种级别的锁，日志等特性来实现了事务的ACID，但是这个我们通常是对于一个数据库服务的定义，常见的情况下我们的数据库随着业务发展也会从单实例变成多实例，组成主从Master-Slave架构，这个时候其实会有一些问题随之出现，比如说主从同步延迟，假如在业务代码中做了读写分离，对于一些敏感度较低的数据其实问题不是很大，只要主从延迟不到特别夸张的地步一般都是可以忍受的，但是对于一些核心的业务数据，比如订单之类的，不能忍受数据不一致，下了单了，付了款了，一刷订单列表，发现这个订单还没支付，甚至订单都没在，这对于用户来讲是恨不能容忍的错误，那么这里就需要一些措施，要不就不读写分离，要不就在 redis 这类缓存下订单，或者支付后加个延时等，这些都是一些补偿措施，并且这也是一个不太切当的例子，比较合适的例子也可以用这个下单来说，一般在电商平台下单会有挺多要做的事情，比如像下面这个图</p>
<p><img data-src="https://mystore-1255223546.cos.ap-chengdu.myqcloud.com/uPic/WX20200517-2127322x.png"></p>
<p>下单的是后要冻结核销优惠券，如果账户里有钱要冻结扣除账户里的钱，如果使用了J 豆也一样，可能还有 E 卡，忽略我借用的平台，因为目前一般后台服务化之后，可能每一项都是对应的一个后台服务，我们期望的执行过程是要不全成功，要不就全保持执行前状态，不能是部分扣减核销成功了，部分还不行，所以我们处理这种情况会引入一些通用的方案，第一种叫<a href="https://zh.wikipedia.org/wiki/%E4%BA%8C%E9%98%B6%E6%AE%B5%E6%8F%90%E4%BA%A4">二阶段提交</a>,</p>
<blockquote>
<p><strong>二阶段提交</strong>（英语：Two-phase Commit）是指在<a href="https://zh.wikipedia.org/wiki/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C">计算机网络</a>以及<a href="https://zh.wikipedia.org/wiki/%E6%95%B0%E6%8D%AE%E5%BA%93">数据库</a>领域内，为了使基于<a href="https://zh.wikipedia.org/wiki/%E5%88%86%E5%B8%83%E5%BC%8F%E7%B3%BB%E7%BB%9F">分布式系统</a>架构下的所有节点在进行<a href="https://zh.wikipedia.org/wiki/%E6%95%B0%E6%8D%AE%E5%BA%93%E4%BA%8B%E5%8A%A1">事务</a>提交时保持一致性而设计的一种<a href="https://zh.wikipedia.org/wiki/%E6%BC%94%E7%AE%97%E6%B3%95">算法</a>。通常，<strong>二阶段提交</strong>也被称为是一种<strong>协议</strong>（Protocol）。在分布式系统中，每个节点虽然可以知晓自己的操作时成功或者失败，却无法知道其他节点的操作的成功或失败。当一个事务跨越多个节点时，为了保持事务的<a href="https://zh.wikipedia.org/wiki/ACID">ACID</a>特性，需要引入一个作为<strong>协调者</strong>的组件来统一掌控所有节点（称作<strong>参与者</strong>）的操作结果并最终指示这些节点是否要把操作结果进行真正的提交（比如将更新后的数据写入磁盘等等）。因此，二阶段提交的算法思路可以概括为： 参与者将操作成败通知协调者，再由协调者根据所有参与者的反馈情报决定各参与者是否要提交操作还是中止操作。</p>
</blockquote>
<p>对于上面的例子，我们将整个过程分成两个阶段，首先是提交请求阶段，这个阶段大概需要做的是确定资源存在，锁定资源，可能还要做好失败后回滚的准备，如果这些都 ok 了那么就响应成功，这里其实用到了一个叫事务的协调者的角色，类似于裁判员，每个节点都反馈第一阶段成功后，开始执行第二阶段，也就是实际执行操作，这里也是需要所有节点都反馈成功后才是执行成功，要不就是失败回滚。其实常用的分布式事务的解决方案主要也是基于此方案的改进，比如后面介绍的<a href="https://zh.wikipedia.org/wiki/%E4%B8%89%E9%98%B6%E6%AE%B5%E6%8F%90%E4%BA%A4">三阶段提交</a>，有三阶段提交就是因为二阶段提交比较尴尬的几个点，</p>
<ul>
<li>第一是对于两阶段提交，其中默认只有协调者有超时时间，当一个参与者进入卡死状态时只能依赖协调者的超时来结束任务，这中间的时间参与者都是锁定着资源</li>
<li>第二是协调者的单点问题，万一挂了，参与者就会在那傻等着</li>
</ul>
<p>所以三阶段提交引入了各节点的超时机制和一个准备阶段，首先是一个<code>can commit</code>阶段，询问下各个节点有没有资源，能不能进行操作，这个阶段不阻塞，只是提前做个摸底，这个阶段其实人畜无害，但是能提高成功率，在这个阶段如果就有节点反馈是不接受的，那就不用执行下去了，也没有锁资源，然后第二阶段是 <code>pre commit</code> ，这个阶段做的事情跟原来的 第一阶段比较类似，然后是第三阶段<code>do commit</code>，其实三阶段提交我个人觉得只是加了个超时，和准备阶段，好像木有根本性的解决的两阶段提交的问题，后续可以再看看一些论文来思考讨论下。</p>
<p>2020年05月24日22:11 更新<br>这里跟朋友讨论了下，好像想通了最核心的一点，对于前面说的那个场景，如果是两阶段提交，如果各个节点中有一个没回应，并且协调者也挂了，这个时候会有什么情况呢，再加一个假设，其实比如这个一阶段其实是检验就失败的，理论上应该大家都释放资源，那么对于这种异常情况，其他的参与者就不知所措了，就傻傻地锁着资源阻塞着，那么三阶段提交的意义就出现了，把第一阶段拆开，那么即使在这个阶段出现上述的异常，即也不会锁定资源，同时参与者也有超时机制，在第二阶段锁定资源出现异常是，其他参与者节点等超时后就自动释放资源了，也就没啥问题了，不过对于那种异常恢复后的一些情况还是没有很好地解决，需要借助 zk 等，后面有空可以讲讲 paxos 跟 raft 等</p>
]]></content>
      <categories>
        <category>分布式事务</category>
        <category>两阶段提交</category>
        <category>三阶段提交</category>
      </categories>
      <tags>
        <tag>分布式事务</tag>
        <tag>两阶段提交</tag>
        <tag>三阶段提交</tag>
        <tag>2PC</tag>
        <tag>3PC</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊最近平淡的生活之又聊通勤</title>
    <url>/2021/11/07/%E8%81%8A%E8%81%8A%E6%9C%80%E8%BF%91%E5%B9%B3%E6%B7%A1%E7%9A%84%E7%94%9F%E6%B4%BB/</url>
    <content><![CDATA[<p>一直以来过着特别平淡普通的生活，不过大多数人应该都这样吧，也许有些人可以把平凡的生活过得精彩，最简单的说明就是朋友圈吧，看我一年的盆友圈虽然在发，不过大概 90%的都是发发跑步的打卡，偶尔会有稀稀拉拉的点赞，天天上班，也不喜欢发什么状态，觉得没什么人关注，索性不发。</p>
<p>只是这么平淡的生活就有一些自己比较心烦纠结的，之前有提到过的交通，最近似乎又发现了一点，就真相总是让人跌破眼镜，以前觉得我可能是胆子比较小，所以会觉得怎么路上这些电瓶都是这么肆无忌惮的往我冲过来，后面慢慢有一种借用电视剧读心神探的概念，安全距离，觉得大部分人跟我一样，骑电瓶车什么的总还是有个安全距离，只是可能这个安全距离对于不同的人不一样，那些骑电瓶车的潜意识里的安全距离是非常短，所以经常会骑车离着你非常近才会刹车，但是这个安全距离理论最近又被推翻了，因为经历过几次电瓶车就是已经跟你有身体接触了，但是没到把人撞倒的程度，似乎这些骑电瓶车的觉得步行的行人在人行道上是空气，蹭一下也无所谓，反正不能挡我的路，总感觉要不是我在前面骑自行车太慢挡着电瓶车，不然他们都能起飞去干掉 F35 解放湾湾了；</p>
<p>另一个问题应该是说我们交通规则普及的太少，虽然我们没有路权这个名词概念，但是其实是有这个优先级的，包括像杭州是以公交车在人行道礼让行人闻名的，其实这个文明的行为只限于人行道在直行路中间的，大部分在十字路口，右转的公交车很少会让直行人行道的，前提是直行的绿灯的时候，特别是像公交车这样，车身特别长，右转的时候会有比较大的死角，如果是公交车先转，行人或者自行车很容易被卷进去，非常危险的，私家车就更不用说了，反正右转即使人行道上人非常多要转的也是一秒都不等，所以我自己在开车的时候是尽量在右转的时候等人行道上的行人或者骑车的走完，因为总会觉得我是不是有点双标，骑车走路的时候希望开车的能按规则让我，自己开车的时候又想赶紧开走，所以在开车的时候尽量做到让行车和骑车的。</p>
<p>还有个其实是写着写着想起来的，比如我骑车左转的时候，因为我是左转到对角那就到了，跟那些左转后要再直行的不一样，我们应该在学车的时候也学过，超车要从左边超，但是往往那些骑电瓶车的在左转的时候会从我右边超过来再往左边撇过去，如果留的空间大还好，有些电瓶车就是如果车头超过了就不管他的车屁股，如果我不减速，自行车就被刮倒了，可能的确是别人就不是人，只要不把你撞倒就无所谓，反正为了你自己不被撞倒你肯定会让的。</p>
]]></content>
      <categories>
        <category>生活</category>
      </categories>
      <tags>
        <tag>生活</tag>
        <tag>糟心事</tag>
        <tag>规则</tag>
        <tag>电瓶车</tag>
        <tag>骑车</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊最近平淡的生活之看《神探狄仁杰》</title>
    <url>/2021/12/19/%E8%81%8A%E8%81%8A%E6%9C%80%E8%BF%91%E5%B9%B3%E6%B7%A1%E7%9A%84%E7%94%9F%E6%B4%BB%E4%B9%8B%E7%9C%8B%E3%80%8A%E7%A5%9E%E6%8E%A2%E7%8B%84%E4%BB%81%E6%9D%B0%E3%80%8B/</url>
    <content><![CDATA[<p>其实最近看的不止这一部，前面看了《继承者们》，《少年包青天》这些，就一起聊下，其中看《继承者们》算是个人比较喜欢，以前就有这种看剧的习惯，这个跟《一生一世》里任嘉伦说自己看《寻秦记》看了几十遍一样，我看喜欢的剧也基本上会看不止五遍，继承者们是有帅哥美女看，而且印象中剧情也挺甜的，一般情况下最好是已经有点遗忘剧情了，因为我个人觉得看剧分两种，无聊了又心情不太好，可以看些这类轻松又看过的剧，可以不完全专心地看剧，另外有心情专心看的时候，可以看一些需要思考，一些探案类的或者烧脑类。<br>最近看了《神探狄仁杰》，因为跟前面看的《少年包青天》都是这类古装探案剧，正好有些感想，《少年包青天》算是儿时阴影，本来是不太会去看的，正好有一次有机会跟 LD 一起看了会就也觉得比较有意思就看了下去，不得不说，以前的这些剧还是很不错的，包括剧情和演员，第一部一共是 40 集，看的过程中也发现了大概是五个案子，平均八集一个案子，整体节奏还是比较慢的，但是基本每个案子其实都是构思得很巧妙，很久以前看过但是现在基本不太记得剧情了，每个案子在前面几集的时候基本都猜不到犯案逻辑，但是在看了狄仁杰之后，发现两部剧也有比较大的差别，少年包青天相对来说逻辑性会更强一些，个人主观觉得推理的严谨性更高，可能剧本打磨上更将就一下，而狄仁杰因为要提现他的个人强项，不比少年包青天中有公孙策一时瑜亮的情节，狄仁杰中分工明确，李元芳是个武力担当，曾泰是捧哏的，相对来说是狄仁杰在案子里从始至终地推进案情，有些甚至有些玄乎，会有一些跳脱跟不合理，有些像是狄仁杰的奇遇，不过这些想法是私人的观点，并不是想要评孰优孰劣；第二个感受是不知道是不是年代关系，特别是少年包青天，每个案件的大 boss 基本都不是个完全的坏人，甚至都是比较情有可原的可怜人，因为一些特殊原因，而好几个都是包拯身边的人，这一点其实跟狄仁杰里第一个使团惊魂案件比较类似，虎敬晖也是个人物形象比较丰满的角色，不是个标签化的淡薄形象，跟金木兰的感情和反叛行动在最后都说明的缘由，而且也有随着跟狄仁杰一起办案被其影响感化，最终为了救狄仁杰而被金木兰所杀，只是这样金木兰这个角色就会有些偏执和符号化，当然剧本肯定不是能面面俱到，这样的剧本已经比现在很多流量剧的好很多了。还想到了前阵子看的《指环王》中的白袍萨鲁曼在剧中也是个比较单薄的角色，这样的电影彪炳影史也没办法把个个人物都设计得完整有血有肉，或者说这本来也是应该有侧重点，当然其实我也不觉得指环王就是绝对的最好的，因为相对来说故事情节的复杂性等真的不如西游记，只是在 86 版之后的各种乱七八糟的翻牌和乱拍已经让这个真正的王者神话故事有点力不从心，这里边有部西游记后传是个人还比较喜欢的，虽然武打动作比较鬼畜，但是剧情基本是无敌的，在西游的架构上衍生出来这么完整丰富的故事，人物角色也都有各自的出彩点。<br>说回狄仁杰，在这之前也看过徐克拍的几部狄仁杰的电影版，第一部刘德华拍得相对完成度更高，故事性也可圈可点，后面几部就是剧情拉胯，靠特效拉回来一点分，虽说这个也是所谓的狄仁杰宇宙的构思在里面但是现在来看基本是跟西游那些差不多，完全没有整体性可言，打一枪换一个地方，演员也没有延续性，剧情也是前后跳脱，没什么关联跟承上启下，导致质量层次不一，更不用谈什么狄仁杰宇宙了，不过这个事情也是难说，原因很多，现在资本都是更加趋利的，一些需要更长久时间才能有回报的投资是很难获得资本青睐，所以只能将重心投给选择一些流量明星，而本来应该将资源投给剧本打磨的基本就没了，再深入说也没意义了，社会现状就是这样。<br>还有一点感想是，以前的剧里的拍摄环境还是比较惨的，看着一些房子，甚至皇宫都是比较破旧的，地面还是石板这种，想想以前的演员的环境再想想现在的，比如成龙说的，以前他拍剧就是啪摔了，问这条有没有过，过了就直接送医院，而不是现在可能手蹭破点皮就大叫，甚至还有饭圈这些破事。</p>
]]></content>
      <categories>
        <category>生活</category>
      </categories>
      <tags>
        <tag>生活</tag>
        <tag>看剧</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊最近平淡的生活之看看老剧</title>
    <url>/2021/11/21/%E8%81%8A%E8%81%8A%E6%9C%80%E8%BF%91%E5%B9%B3%E6%B7%A1%E7%9A%84%E7%94%9F%E6%B4%BB%E4%B9%8B%E7%9C%8B%E7%9C%8B%E8%80%81%E5%89%A7/</url>
    <content><![CDATA[<p>最近因为也没什么好看的新剧和综艺所以就看看一些以前看过的老剧，我是个非常念旧的人吧，很多剧都会反反复复地看，一方面之前看过觉得好看的的确是一直记着，还有就是平时工作完了回来就想能放松下，剧情太纠结的，太烧脑的都不喜欢，也就是我常挂在口头的不喜欢看费脑子的剧，跟我不喜欢狼人杀的原因也类似。</p>
<p>前面其实是看的太阳的后裔，跟 LD 一起看的，之前其实算是看过一点，但是没有看的很完整，并且很多剧情也忘了，只是这个我我可能看得更少一点，因为最开始的时候觉得男主应该是男二，可能对长得这样的男主并且是这样的人设有点失望，感觉不是特别像个特种兵，但是由于本来也比较火，而且 LD 比较喜欢就从这个开始看了，有两个点是比较想说的</p>
<p>韩剧虽然被吐槽的很多，但是很多剧的质量，情节把控还是优于目前非常多国内剧的，相对来说剧情发展的前后承接不是那么硬凹出来的，而且人设都立得住，这个是非常重要的，很多国内剧怎么说呢，就是当爹的看起来就比儿子没大几岁，三四十岁的人去演一个十岁出头的小姑娘，除非容貌异常，比如刘晓庆这种，不然就会觉得导演在把我们观众当傻子。瞬间就没有想看下去的欲望了。</p>
<p>再一点就是情节是大众都能接受度比较高的，现在有很多普遍会找一些新奇的视角，比如卖腐，想某某令，两部都叫某某令，这其实是一个点，延伸出去就是跟前面说的一点有点类似，xx 老祖，人看着就二三十，叫 xx 老祖，（喜欢的人轻喷哈）然后名字有一堆，同一个人物一会叫这个名字，一会又叫另一个名字，然后一堆死表情。</p>
<p>因为今天有个特殊的事情发生，所以简短的写（shui）一篇了</p>
]]></content>
      <categories>
        <category>生活</category>
      </categories>
      <tags>
        <tag>生活</tag>
        <tag>看剧</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊给亲戚朋友的老电脑重装系统那些事儿</title>
    <url>/2021/05/09/%E8%81%8A%E8%81%8A%E7%BB%99%E4%BA%B2%E6%88%9A%E6%9C%8B%E5%8F%8B%E7%9A%84%E8%80%81%E7%94%B5%E8%84%91%E9%87%8D%E8%A3%85%E7%B3%BB%E7%BB%9F%E9%82%A3%E4%BA%9B%E4%BA%8B%E5%84%BF/</url>
    <content><![CDATA[<p>前面这个五一回去之前，LD 姐姐跟我说电脑很卡了，想让我重装系统，问了下 LD 可能是那个 09 年买的笔记本，想想有点害怕[捂脸]，前年有一次好像让我帮忙装了她同事的一个三星的笔记本，本着一些系统洁癖，所以就从开始找纯净版的 win7 家庭版，因为之前那些本基本都自带 win7 的家庭版，而且把激活码就贴在机器下面，然后从三星官网去找官方驱动，还好这个机型的驱动还在，先做了系统镜像，其实感觉这种情况需要两个 U 盘，一个 U 盘装系统作为安装启动盘，一个放驱动，毕竟不是专业装系统的，然后因为官方驱动需要一个个下载一个个安装，然后驱动文件下载的地方还没标明是 32 位还是 64 位的，结果还被 LD 姐姐催着，一直问好没好，略尴尬，索性还是找个一键安装的</p>
<p>这次甚至更夸张，上次还让带回去，我准备好了系统镜像啥的，第二天装，这次直接带了两个老旧笔记本过来说让当天就装好，感觉有点像被当修电脑的使，又说这些电脑其实都不用了的，都是为了她们当医生的要每年看会课，然后只能用电脑浏览器看，结果都在用 360 浏览器，真的是万恶的 360，其实以前对 360 没啥坏印象，毕竟以前也经常用，只是对于这些老电脑，360 全家桶真的就是装了就废了，2G 的内存，开机就开着 360 安全卫士，360 杀毒，有一个还装了腾讯电脑管家，然后腾讯视频跟爱奇艺也开机启动了，然后还打开 360 浏览器看课，就算再好的系统也吃不消这么用，重装了系统，还是这么装这些东西，也是分分钟变卡，可惜他们都没啥这类概念。</p>
<p>对于他们要看的课，更搞笑的是，明明在页面上注明了说要使用 IE 浏览器，结果他们都在用 360 浏览器看，但是这个也不能完全怪他们，因为实在是现在的 IE 啥的也有开始不兼容 flash 的配置，需要开启兼容配置，但是只要开启了之后就可以直接用 IE 看，比 360 靠谱很多， 资源占用也比较少，360 估计是基于 chromium 加了很多内置的插件，本身 chromium 也是内存大户，但是说这些其实他们也不懂，总觉得找我免费装下系统能撑一段时间，反正对我来说也应该很简单（他们觉得），实际上开始工作以后，我自己想装个双系统都是上淘宝买别人的服务装的，台式机更是几年没动过系统了，因为要重装一大堆软件，数据备份啥的，还有驱动什么的，分区格式，那些驱动精灵啥的也都是越来越坑，一装就给你带一堆垃圾软件。</p>
<p>感悟是，总觉得学计算机的就应该会装系统，会修电脑，之前亲戚还拿着一个完全开不起来的笔记本让我来修，这真的是，我说可以找官方维修的，结果我说我搞不定，她直接觉得是修不好了，直接电脑都懒得拿回去了，后面又一次反复解释了才明白，另外就是 360 全家桶，别说老电脑了，新机器都不太吃得消。</p>
]]></content>
      <categories>
        <category>生活</category>
      </categories>
      <tags>
        <tag>生活</tag>
        <tag>装电脑</tag>
        <tag>老电脑</tag>
        <tag>360 全家桶</tag>
        <tag>修电脑的</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊那些加塞狗</title>
    <url>/2021/01/17/%E8%81%8A%E8%81%8A%E9%82%A3%E4%BA%9B%E5%8A%A0%E5%A1%9E%E7%8B%97/</url>
    <content><![CDATA[<p>今天真的是被气得不轻，情况是碰到一个有 70 多秒的直行红灯，然后直行就排了很长的队，但是左转车道没车，就有好几辆车占着左转车道，准备往直行车道插队加塞，一般这种加塞的，会挑个不太计较的，如果前面一辆不让的话就再等等，我因为赶着回家，就不想让，结果那辆车几次车头直接往里冲，当时怒气值基本已经蓄满了，我真的是分毫都不想让，如果路上都是让着这种人的，那么这种情况只会越来越严重，我理解的这种心态，就赌你怕麻烦，多一事不如少一事，结果就是每次都能顺利插队加塞，其实延伸到我们社会中的种种实质性的排队或者等同于排队的情况，都已经有这种惯有思维，一方面这种不符合规则，可能在严重程度上容易被很多人所忽视，基本上已经被很多人当成是“合理”行为，另一方面，对于这些“微小”的违规行为，本身管理层面也基本没有想要管的意思，就更多的成为了纵容这些行为的导火索，并且大多数人都是想着如果不让，发生点小剐小蹭的要浪费很多时间精力来处理，甚至会觉得会被别人觉得自己太小气等等，诸多内外成本结合起来，会真的去硬刚的可能少之又少了，这样也就让更多的人觉得这种行为是被默许的，再举个非常小的例子，以我们公司疫情期间的盒饭发放为例，有两个比较“有意思”的事情，第一个就是因为疫情，本来是让排队要间隔一米，但是可能除了我比较怕死会跟前面的人保持点距离基本没别人会不挨着前面的人，甚至我跟我前面的人保持点距离，后面的同学会推着我让我上去；第二个是关于拿饭，这么多人排着队拿饭，然后有部分同学，一个人拿好几份，帮组里其他人的都拿了，有些甚至一个人拿十份，假如这个盒饭发放是说明了可以按部门直接全领了那就没啥问题，但是当时的状况是个人排队领自己的那一份，如果一个同学直接帮着组里十几个人都拿了，后面排队的人是什么感受呢，甚至有些是看到队伍排长了，就找队伍里自己认识的比较靠前的人说你帮我也拿一份，其实作为我这个比较按规矩办事的“愣头青”来说，我是比较不能接受这两件小事里的行为的，再往下说可能就有点偏激了，先说到这~</p>
]]></content>
      <categories>
        <category>生活</category>
        <category>开车</category>
      </categories>
      <tags>
        <tag>生活</tag>
        <tag>开车</tag>
        <tag>加塞</tag>
        <tag>糟心事</tag>
        <tag>规则</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊最近平淡的生活之《花束般的恋爱》观后感</title>
    <url>/2021/12/31/%E8%81%8A%E8%81%8A%E6%9C%80%E8%BF%91%E5%B9%B3%E6%B7%A1%E7%9A%84%E7%94%9F%E6%B4%BB%E4%B9%8B%E3%80%8A%E8%8A%B1%E6%9D%9F%E8%88%AC%E7%9A%84%E6%81%8B%E7%88%B1%E3%80%8B%E8%A7%82%E5%90%8E%E6%84%9F/</url>
    <content><![CDATA[<p>周末在领导的提议下看了豆瓣的年度榜单，本来感觉没啥心情看的，看到主演有有村架纯就觉得可以看一下，颜值即正义嘛，男主小麦跟女主小娟（后面简称小麦跟小娟）是两个在一次非常偶然的没赶上地铁末班车事件中相识，这里得说下日本这种通宵营业的店好像挺不错的，看着也挺正常，国内估计只有酒吧之类的可以。晚上去的地方是有点暗暗的，好像也有点类似酒吧，旁边有类似于 dj 那种，然后同桌的还有除了男女主的另外一对男女，也是因为没赶上地铁末班车的，但也是陌生人，然后小麦突然看到了有个非常有名的电影人，小娟竟然也认识，然后旁边那对完全不认识，还在那吹自己看过很多电影，比如《肖申克的救赎》，于是男女主都特别鄙夷地看着他们，然后他们又去了另一个有点像泡澡的地方席地而坐，他们发现了自己的鞋子都是一样的，然后在女的去上厕所的时候，小麦暗恋的学姐也来了，然后小麦就去跟学姐他们一起坐了，小娟回来后有点不开心就说去朋友家睡，幸好小麦看出来了（他竟然看出来了，本来以为应该是没填过恋爱很木讷的），就追出去，然后就去了小麦家，到了家小娟发现小麦家的书柜上的书简直就跟她自己家的一模一样，小麦还给小娟吹了头发，一起吃烤饭团，看电影，第二天送小娟上了公交，还约好了一起看木乃伊展，然而并没有交换联系方式，但是他们还是约上了一起看了木乃伊展，在餐馆就出现了片头那一幕的来源，因为餐馆他们想一起听歌，就用有线耳机一人一个耳朵听，但是旁边就有个大叔说“你们是不是不爱音乐，左右耳朵是不一样的，只有一起听才是真正的音乐”这样的话，然后的剧情有点跳，因为是指他们一直在这家餐馆吃饭，中间有他们一起出去玩情节穿插着，也是在这他们确立了关系，可以说主体就是体现了他们非常的合拍和默契，就像一些影评说的，这部电影是说如何跟百分百合拍的人分手，然后就是正常的恋爱开始啪啪啪，一直腻在床上，也没去就业说明会，后面也有讲了一点小麦带着小娟去认识他的朋友，也把小娟介绍给了他们认识，这里算是个小伏笔，后面他们分手也有这里的人的一些关系，接下去的剧情说实话我是不太喜欢的，如果一部八分的电影只是说恋爱被现实打败的话，我觉得在我这是不合格的，但是事实也是这样，小麦其实是有家里的资助，所以后面还是按自己的喜好给一些机构画点插画，小娟则要出去工作，因为小娟家庭观念也是要让她出去有正经工作，用脚指头想也能知道肯定不顺利，然后就是暂时在一家蛋糕店工作，小麦就每天去接小娟，日子过得甜甜蜜蜜，后面小娟在自己的努力下考了个什么资格证，去了一家医院还是什么做前台行政，这中间当然就有父母来见面吃饭了，他们在开始恋爱不久就同居合租了，然后小娟父母就是来说要让她有个正经工作，对男的说的话就是人生就是责任这类的话，而小麦爸爸算是个导火索，因为小麦家里是做烟花生意的，他爸让他就做烟花生意，因为要回老家，并且小麦也不想做，所以就拒绝了，然后他爸就说不给他每个月五万的资助，这也导致了小麦需要去找工作，这个过程也是很辛苦，本来想要年前找好工作，然后事与愿违，后面有一次小娟被同事吐槽怎么从来不去团建，于是她就去了（我以为会拒绝），正在团建的时候小麦给她电话，说找到工作了，是一个创业物流公司这种，这里剧情就是我觉得比较俗套的，小麦各种被虐，累成狗，但是就像小娟爸爸说的话，人生就是责任，所以一直在坚持，但是这样也导致了跟小娟的交流也越来越少，他们原来最爱的漫画，爱玩的游戏，也只剩小娟一个人看，一个人玩，而正是这个时候，小娟说她辞掉了工作，去做一个不是太靠谱的漫画改造的密室逃脱，然后这里其实有一点后面争议很大的，就是这个工作其实是前面小麦介绍给小娟的那些朋友中一个的女朋友介绍的，而在有个剧情就是小娟有一次在这个密室逃脱的老板怀里醒过来，是在 KTV 那样的场景里，这就有很多人觉得小娟是不是出轨了，我觉得其实不那么重要，因为这个离职的事情已经让一切矛盾都摆在眼前，小麦其实是接受这种需要承担责任的生活，也想着要跟小娟结婚，但是小娟似乎还是想要过着那样理想的生活，做自己想做的事情，看自己爱看的漫画，也要小麦能像以前那样一直那么默契的有着相同的爱好，这里的触发点其实还有个是那个小麦的朋友（也就是他女朋友介绍小娟那个不靠谱工作的）的葬礼上，小麦在参加完葬礼后有挺多想倾诉的，而小娟只是想睡了，这个让小麦第二天起来都不想理小娟，只是这里我不太理解，难道这点闹情绪都不能接受吗，所谓的合拍也只是毫无限制的情况下的合拍吧，真正的生活怎么可能如此理想呢，即使没有物质生活的压力，也会有其他的各种压力和限制，在这之后其实小麦想说的是小娟是不是没有想跟自己继续在一起的想法了，而小娟觉得都不说话了，还怎么结婚呢，后面其实导演搞了个小 trick，突然放了异常婚礼，但是不是男女主的，我并不觉得这个桥段很好，在婚礼里男女主都觉得自己想要跟对方说分手了，但是当他们去了最开始一直去的餐馆的时候，一个算是一个现实映照的就是他们一直坐的位子被占了，可能也是导演想通过这个来说明他们已经回不去了，在餐馆交谈的时候，小麦其实是说他们结婚吧，并没有想前面婚礼上预设地要分手，但是小娟放弃了，不想结婚，因为不想过那样的生活了，而小麦觉得可能生活就是那样，不可能一直保持刚恋爱时候的那种感觉，生活就是责任，人生就意味着责任。</p>
<p>我的一些观点也在前面说了，恋爱到婚姻，即使物质没问题，经济没问题，也会有各种各样的问题，需要一起去解决，因为结婚就意味着需要相互扶持，而不是各取所需，可能我的要求比较高，后面男女主在分手后还一起住了一段时间，我原来还在想会不会通过这个方式让他们继续去磨合同步，只是我失望了，最后给个打分可能是 5 到 6 分吧，勉强及格，好的影视剧应该源于生活高于生活，这一部可能还比不上生活。</p>
]]></content>
      <categories>
        <category>生活</category>
      </categories>
      <tags>
        <tag>生活</tag>
        <tag>看剧</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊部分公交车的设计bug</title>
    <url>/2021/12/05/%E8%81%8A%E8%81%8A%E9%83%A8%E5%88%86%E5%85%AC%E4%BA%A4%E8%BD%A6%E7%9A%84%E8%AE%BE%E8%AE%A1bug/</url>
    <content><![CDATA[<p>今天惯例坐公交回住的地方，不小心撞了头，原因是我们想坐倒数第二排，然后LD 走在我后面，我就走到最后一排中间等着，但是最后一排是高一截的，等 LD 坐进去以后，我就往前走，结果撞到了车顶的扶手杆子的一端，差点撞昏了去，这里我觉得其实杆子长度应该短一点，不然从最后一排出来，还是有比较大概率因为没注意看而撞到头，特别是没注意看的情况，发力其实会比较大，一头撞上就会像我这样，眼前一黑，又痛得要死。<br>还有一点就是座位设计了，先来看个图<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/sCM2t1.png"><br>图里大致画了两条线，因为可能是轮胎还是什么原因，后排中间会有那么大的突起，但是看两条红线可以发现，靠近过道的座位边缘跟地面突起的边缘不是一样宽的，这样导致的结果就是坐着的时候有一个脚没地儿搁，要不就得侧着斜着坐，或者就是一个脚悬空，短程的可能还好，路程远一点还是比较难受的，特别是像我现在这样，大腿外侧有点难受的情况，就会更难受。<br>虽然说这两个点，基本是屁用没有，但是我也是在自己这个博客说说，也当是个树洞了。</p>
]]></content>
      <categories>
        <category>生活</category>
      </categories>
      <tags>
        <tag>生活</tag>
        <tag>公交</tag>
        <tag>杭州</tag>
      </tags>
  </entry>
  <entry>
    <title>这周末我又在老丈人家打了天小工</title>
    <url>/2020/08/30/%E8%BF%99%E5%91%A8%E6%9C%AB%E6%88%91%E5%8F%88%E5%9C%A8%E8%80%81%E4%B8%88%E4%BA%BA%E5%AE%B6%E6%89%93%E4%BA%86%E5%A4%A9%E5%B0%8F%E5%B7%A5/</url>
    <content><![CDATA[<p>因为活实在比较多，也不太好叫大工(活比较杂散)，相比上一次我跟 LD 俩人晚起了一点，我真的是只要有事，早上就醒的很早，准备八点出发的，六点就醒了，然后想继续睡就一直做梦🤦‍♂️，差不多八点半多到的丈人家，他们应该已经干了有一会了，我们到了以后就分配给我撬地板的活，上次说的那个敲掉柜子的房间里，还铺着质地还不错的木地板，但是也不想要了，得撬掉重新铺。<br>拿着撬棍和榔头就上楼去干了，浙江这几天的天气，最高温度一般 38、9，楼上那个房间也没风扇，有了也不能用，都是灰尘，撬了两下，我感觉我体内的水就像真气爆发一样变成汗炸了出来，眼睛全被汗糊住了，可能大部分人不太了解地板是怎么铺的，一般是在地面先铺一层混凝土，混凝土中间嵌进去规则的长条木条，然后真正的地板一块块的都是钉在那个木条上，用那种气枪钉和普通的钉子，并且块跟块之前还有一个木头的槽结构相互耦合，然后边缘的一圈在用较薄的木板将整个木地板封边(这些词都是我现造的)，边缘的用的钉子会更多，所以那几下真的很用力，而且撬地板，得蹲下起来，如此反复，对于我这个体重快超过身高的中年人来说的确是非常大的挑战，接下来继续撬了几个，已经有种要虚脱晕倒的感觉了，及时去喝水擦了汗，又歇了一会，为啥一上来就这么拼呢，主要是因为那个房间丈人在干活的时候是直接看得到的🤦‍♂️，后来被 LD 一顿教育，本来就是去帮忙的，又不是专业做这个的，急啥。<br>喝了水之后，又稍稍歇了一会，就开始继续撬了，本来觉得这个地板撬着好像还行，房间不大，没多久就撬完了，撬完之后喝了点饮料(补充点糖分，早餐吃得少，有点低血糖)，然后看到 LD 在撬下面的木条了，这个动作开始了那天最大的经验值收集行动，前面说了这个木条一般是跟混凝土一块铺上去的，但是谁也没想到，这个混凝土铺上去的时候竟然处理的这么随意，根本没考虑跟下面的贴合，所以撬木条的时候直接把木条跟木条中间大块大块的混凝土一块撬起来了，想想那重量，于是我这靠蛮力干活的，就用力把木条带着混凝土一块撬了起来，还沾沾自喜，但是发现结果是撬起来一块之后，体力值瞬间归零，上一篇我也提到了，其实干这类活也是很有技巧性的，但是上次的是我没学会，可能需要花时间学的，但是这次是LD 用她的纤细胳膊教会我的，我在撬的时候，屏住一口气，双手用力，起，大概是吃好几口奶的力气都用出来了，但是 LD 在我休息的时候，慢慢悠悠的，先把撬棍挤到木条或者混凝土跟下层的缝里，然后往下垫一小块混凝土碎石，然后轻轻松松的扳两下，就撬开了，亏我高中的时候引以为傲的物理成绩，作为物理课代表，这么浅显易懂的杠杆原理都完全不会用到生活里，后面在用这个技巧撬的过程中，真的觉得自己蠢到家了，当然在明白了用点杠杆原理之后，撬地板的活就变得慢慢悠悠，悠哉悠哉的了(其实还是很热的，披着毛巾擦眼睛)。<br>上午的活差不多完了，后面就是把撬出来的混凝土和地板条丢下去，地上铺着不用了的被子，然后就是午饭和午休环节了，午饭换了一家快餐，味道非常可以，下午的活就比较单调了，帮忙清理了上去扔下来的混凝土碎块跟木条，然后稍微打扫了下，老丈人就让我们回家了，接着上次说的，还是觉得比跑步啥的消耗大太多了，那汗流的，一口就能喝完一瓶 500 毫升左右的矿泉水。</p>
]]></content>
      <categories>
        <category>生活</category>
        <category>运动</category>
        <category>跑步</category>
        <category>干活</category>
      </categories>
      <tags>
        <tag>生活</tag>
        <tag>运动</tag>
        <tag>减肥</tag>
        <tag>跑步</tag>
        <tag>干活</tag>
      </tags>
  </entry>
  <entry>
    <title>重看了下《蛮荒记》说说感受</title>
    <url>/2021/10/10/%E9%87%8D%E7%9C%8B%E4%BA%86%E4%B8%8B%E3%80%8A%E8%9B%AE%E8%8D%92%E8%AE%B0%E3%80%8B%E8%AF%B4%E8%AF%B4%E6%84%9F%E5%8F%97/</url>
    <content><![CDATA[<p>周末把《蛮荒记》看完了，前面是发现微信读书有《搜神记》和《蛮荒记》，但是《搜神记》看了会发现很多都是跳段了，不知道为啥，貌似也没什么少儿不宜的情节，所以就上网找了原版来看，为什么看这个呢，主要还是高中的时候看过，觉得写得很不错，属于那时候的玄幻小说里的独一档，基于山海经创造了一个半架空的大荒宇宙，五族帝尊，人物名都是听说过的，而且又能契合部分历史，整个故事布局非常宏大，并且情节矛盾埋得很深，这里就不对具体情节作介绍了，只是聊聊对书中的一些人物和情节的看法感受。</p>
<p>乌丝兰玛是个贯穿两部，甚至在蛮荒的最后还要再搞事情，极其坚定的自以为是的大 boss，其实除了最后被我们的主人公打败，前面几乎就是无所不能，下了一盘无比巨大的棋，主人公都只是其中一个棋子和意外，但是正如很多反派，一直以来都是背着一个信念，并且这个所谓的信念是比较正义的，只是为了这个正义的信念和目标却做了各种丧尽天良的事情，说起来跟灭霸有点像，为了环保哈哈，相对来说感觉姬远玄也只是个最大牌的工具人，或者说是中间人，深爱的妹妹冰夷也意外被蚩尤怒拿一血。</p>
<p>但是中间那个赤霞仙子一定要给烈烟石的心上锁，导致最后认不出来蚩尤，也间接导致了蚩尤被杀，如果不考虑最后情节或者推动故事的需求，这个还是我很讨厌的，有点类似于《驴得水》里那个校长，看着貌似是个正常的，做的事情也是正派，但是其实是害人不浅，即使南阳仙子因此被抛进了火山，那也是有贱人在那挑食，并且赤松子是赤飚怒的儿子，烈烟石跟蚩尤又没这层关系，就很像倚天屠龙记里的灭绝师太和极品家丁里的那个玉德仙坊的院主，后者还好一些，前者几乎就是导致周芷若一生悲剧的始作俑者，自己偏执的善恶观，还要给徒弟灌输如此恶毒的理念和让她立下像紧箍咒似的誓言，在人一生中本来就有很多不能如愿的，又被最亲最尊敬的人下了这样的紧箍咒，人生的不幸也加倍了。</p>
<p>似乎习惯了总要有个总结的，想说的应该是我觉得这些剧也好，书也好，我觉得最坏的人可能是大部分人眼中的一些次要人物，或者至少大 boss 才是最坏的人，当然这个坏也不是严格的二分法，只是我觉得最让我觉得负面的人物，这些人可能看起来情景出现的不多，只是说了很少的话，做了很少的事，但是在我看来却做了最大的恶。</p>
]]></content>
      <categories>
        <category>生活</category>
      </categories>
      <tags>
        <tag>生活</tag>
        <tag>看书</tag>
      </tags>
  </entry>
  <entry>
    <title>闲聊下乘公交的用户体验</title>
    <url>/2021/02/28/%E9%97%B2%E8%81%8A%E4%B8%8B%E4%B9%98%E5%85%AC%E4%BA%A4%E7%9A%84%E7%94%A8%E6%88%B7%E4%BD%93%E9%AA%8C/</url>
    <content><![CDATA[<p>新年开工开车来杭州，因为没有车位加限行今天来就没开车来了，从东站做公交回住的地方，这班神奇的车我之前也吐槽过了，有神奇的乘客和神奇的司机，因为基本上这班车是从我毕业就开始乘了，所以也算是比较熟悉了，以前总体感觉不太好的是乘坐时间太长了，不过这个也不能怪车，是我自己住得远（离东站），后来住到了现在的地方，也算是直达，并且 LD 比较喜欢直达的，不爱更快却要换乘的地铁，所以坐的频率比较高，也说过前面那些比较气人的乘客，自己不好好戴口罩，反而联合一起上车的乘客诽谤司机，说他要吃人了要打人了，也正是这个司机比较有意思，上车就让戴好口罩，还给大家讲，哪里哪里又有疫情了，我觉得其实这个司机还是不错的，特殊时期，对于这种公共交通，这样的确是比较负责任的做法，只是说话方式，语气这个因人而异，他也不是来伺候人的，而且这么一大车人，说了一遍不行，再说一遍，三遍以上了，嗓门大一点也属于正常的人的行为。<br>还是说回今天要说的，今天这位司机我看着跟前面说的那位有点像，因为上车的时候比较暗没看清脸，主要原因是这位司机开车比较猛，比较急，然后车上因为这个时间点，比较多大学开学来的学生，拎着个行李箱，一开始是前面已经都站满了人，后面还有很多空位，因为后面没地方放行李箱，就因为这样前面站着的有几个就在说司机开慢点，结果司机貌似也没听进去，还是我行我素，过了会又有人说司机开稳一点，就在这个人说完没一会，停在红绿灯路口的车里，就有人问有没有垃圾桶，接着又让司机开门，说晕车太严重了，要下车，司机开了门，我望出去两个妹子下了车，好像在路边草丛吐了，前面开门下车的时候就有人说她们第一次来杭州，可能有点责怪司机开的不稳，也影响了杭州交通给新来杭州的人的感受，说完了事情经过，其实我有蛮多感触，对于杭州公交司机，我大概是大一来了没多久，陪室友去文三路买电脑就晕车，下车的时候在公交车站吐了，可能是从大学开始缺乏锻炼，又饮食不规律，更加容易晕车，大部分晕车我觉得都是我自己的原因，有时候是上车前吃太多了，或者早上起太早，没睡好，没吃东西，反正自己也是挺多原因的，说到司机的原因的话，我觉得可能这班车还算好的，最让我难受的还是上下班高峰的时候，因为经过的那条路是比较重要的主干道，路比较老比较窄，并且还有很多人行道，所以经常一脚油门连带着一脚刹车，真的很难受，这种算是我觉得真的是公交体验比较差的一点，但是这一点呢也不能完全怪公交司机，杭州的路政规划是很垃圾，没看错，是垃圾，所以总体结论是公交还行，主要是路政规划就是垃圾，包括这条主干道这么多人行道，并且两边都是老小区，老年人在上班高峰可能要买菜送娃或者其他事情，在通畅的情况下可能只需要六分钟的路程，有时候因为各种原因，半小时都开不完，扯开去一点，杭州的路，核心的高速说封就封，本来是高架可以直接通到城西，结果没造，到了路本已经很拥挤的时候开始来造隧道，各种破坏，隧道接高架的地方，无尽的加塞，对于我这样的小白司机来说真的是太恶心了，所以我一直想说的就是杭州这个地方房价领先基础设施十年，地铁，高架，高速通通不行，地面道路就更不行了。<br>总结下，其实杭州的真正的公交体验差，应该还是路造成的，对于前面的那两位妹子来说，有可能是她们来自于公交司机都是开的特别稳，并且路况也很好的地方，也或者是我被虐习惯了🤦‍♂️</p>
]]></content>
      <categories>
        <category>生活</category>
        <category>公交</category>
      </categories>
      <tags>
        <tag>生活</tag>
        <tag>开车</tag>
        <tag>加塞</tag>
        <tag>糟心事</tag>
        <tag>规则</tag>
        <tag>公交</tag>
        <tag>路政规划</tag>
        <tag>基础设施</tag>
        <tag>杭州</tag>
        <tag>高速</tag>
      </tags>
  </entry>
  <entry>
    <title>AQS篇二 之 Condition 浅析笔记</title>
    <url>/2021/02/21/AQS-%E4%B9%8B-Condition-%E6%B5%85%E6%9E%90%E7%AC%94%E8%AE%B0/</url>
    <content><![CDATA[<p>Condition也是 AQS 中很重要的一块内容，可以先看段示例代码，这段代码应该来自于Doug Lea大大，可以在 javadoc 中的 <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/Condition.html">condition</a> 部分找到，其实大大原来写过基于 <code>synchronized</code> 实现的，后面我也贴下代码</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">import</span> <span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span><span class="token class-name">Condition</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span><span class="token class-name">Lock</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span><span class="token class-name">ReentrantLock</span><span class="token punctuation">;</span>

<span class="token keyword">class</span> <span class="token class-name">BoundedBuffer</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">final</span> <span class="token class-name">Lock</span> lock <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ReentrantLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">// condition 依赖于 lock 来产生</span>
    <span class="token keyword">final</span> <span class="token class-name">Condition</span> notFull <span class="token operator">=</span> lock<span class="token punctuation">.</span><span class="token function">newCondition</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">final</span> <span class="token class-name">Condition</span> notEmpty <span class="token operator">=</span> lock<span class="token punctuation">.</span><span class="token function">newCondition</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token comment">// 对象池子，put 跟 take 的就是这里的</span>
    <span class="token keyword">final</span> <span class="token class-name">Object</span><span class="token punctuation">[</span><span class="token punctuation">]</span> items <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Object</span><span class="token punctuation">[</span><span class="token number">100</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
    <span class="token keyword">int</span> putptr<span class="token punctuation">,</span> takeptr<span class="token punctuation">,</span> count<span class="token punctuation">;</span>

    <span class="token comment">// 生产</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">put</span><span class="token punctuation">(</span><span class="token class-name">Object</span> x<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">// 这里也说明了，需要先拥有锁</span>
        lock<span class="token punctuation">.</span><span class="token function">lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">while</span> <span class="token punctuation">(</span>count <span class="token operator">==</span> items<span class="token punctuation">.</span>length<span class="token punctuation">)</span>
                notFull<span class="token punctuation">.</span><span class="token function">await</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  <span class="token comment">// 队列已满，等待，直到 not full 才能继续生产</span>
            items<span class="token punctuation">[</span>putptr<span class="token punctuation">]</span> <span class="token operator">=</span> x<span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">++</span>putptr <span class="token operator">==</span> items<span class="token punctuation">.</span>length<span class="token punctuation">)</span> putptr <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
            <span class="token operator">++</span>count<span class="token punctuation">;</span>
            notEmpty<span class="token punctuation">.</span><span class="token function">signal</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// 生产成功，队列已经 not empty 了，发个通知出去</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">finally</span> <span class="token punctuation">&#123;</span>
            lock<span class="token punctuation">.</span><span class="token function">unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token comment">// 消费</span>
    <span class="token keyword">public</span> <span class="token class-name">Object</span> <span class="token function">take</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span> <span class="token punctuation">&#123;</span>
        lock<span class="token punctuation">.</span><span class="token function">lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">while</span> <span class="token punctuation">(</span>count <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span>
                notEmpty<span class="token punctuation">.</span><span class="token function">await</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// 队列为空，等待，直到队列 not empty，才能继续消费</span>
            <span class="token class-name">Object</span> x <span class="token operator">=</span> items<span class="token punctuation">[</span>takeptr<span class="token punctuation">]</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">++</span>takeptr <span class="token operator">==</span> items<span class="token punctuation">.</span>length<span class="token punctuation">)</span> takeptr <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
            <span class="token operator">--</span>count<span class="token punctuation">;</span>
            notFull<span class="token punctuation">.</span><span class="token function">signal</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// 被我消费掉一个，队列 not full 了，发个通知出去</span>
            <span class="token keyword">return</span> x<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">finally</span> <span class="token punctuation">&#123;</span>
            lock<span class="token punctuation">.</span><span class="token function">unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>介绍下 Condition 的结构</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ConditionObject</span> <span class="token keyword">implements</span> <span class="token class-name">Condition</span><span class="token punctuation">,</span> <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>io<span class="token punctuation">.</span></span>Serializable</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">final</span> <span class="token keyword">long</span> serialVersionUID <span class="token operator">=</span> <span class="token number">1173984872572414699L</span><span class="token punctuation">;</span>
        <span class="token comment">/** First node of condition queue. */</span>
        <span class="token keyword">private</span> <span class="token keyword">transient</span> <span class="token class-name">Node</span> firstWaiter<span class="token punctuation">;</span>
        <span class="token comment">/** Last node of condition queue. */</span>
        <span class="token keyword">private</span> <span class="token keyword">transient</span> <span class="token class-name">Node</span> lastWaiter<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>主要的就这么点，而且也复用了 AQS 阻塞队列或者大大叫 <code>lock queue</code>中同样的 Node 节点，只不过它没有使用其中的双向队列，也就是prev 和 next，而是在 Node 中的 nextWaiter，所以只是个单向的队列，没使用 next 其实还有个用处，后面会提到，看下结构的示意图<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/Ss9oFX.png"><br>然后主要是看两个方法，<code>await</code> 和 <code>signal</code>,<br>先来看下 await</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">/**
 * Implements interruptible condition wait.
 * &lt;ol>
 * &lt;li> If current thread is interrupted, throw InterruptedException.
 * &lt;li> Save lock state returned by &#123;@link #getState&#125;.
 * &lt;li> Invoke &#123;@link #release&#125; with saved state as argument,
 *      throwing IllegalMonitorStateException if it fails.
 * &lt;li> Block until signalled or interrupted.
 * &lt;li> Reacquire by invoking specialized version of
 *      &#123;@link #acquire&#125; with saved state as argument.
 * &lt;li> If interrupted while blocked in step 4, throw InterruptedException.
 * &lt;/ol>
 */</span>
<span class="token keyword">public</span> <span class="token keyword">final</span> <span class="token keyword">void</span> <span class="token function">await</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">interrupted</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
        <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">InterruptedException</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token comment">// 将当前节点包装成一个  condition waiter node 节点</span>
    <span class="token class-name">Node</span> node <span class="token operator">=</span> <span class="token function">addConditionWaiter</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token comment">// 完全释放占有的锁，这里需要是占有锁的线程</span>
    <span class="token keyword">int</span> savedState <span class="token operator">=</span> <span class="token function">fullyRelease</span><span class="token punctuation">(</span>node<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">int</span> interruptMode <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>

    <span class="token comment">// 判断下是否在阻塞队列中，因为有可能被其他节点从等待队列移动到阻塞队列</span>
    <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token function">isOnSyncQueue</span><span class="token punctuation">(</span>node<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">// park等待，等待被唤醒</span>
        <span class="token class-name">LockSupport</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token punctuation">(</span>interruptMode <span class="token operator">=</span> <span class="token function">checkInterruptWhileWaiting</span><span class="token punctuation">(</span>node<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token operator">!=</span> <span class="token number">0</span><span class="token punctuation">)</span>
            <span class="token keyword">break</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token comment">// 被唤醒后进入阻塞队列，等待获取锁，这里继续用了fullyRelease返回的 state</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">acquireQueued</span><span class="token punctuation">(</span>node<span class="token punctuation">,</span> savedState<span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> interruptMode <span class="token operator">!=</span> THROW_IE<span class="token punctuation">)</span>
        interruptMode <span class="token operator">=</span> REINTERRUPT<span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>node<span class="token punctuation">.</span>nextWaiter <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token comment">// clean up if cancelled</span>
        <span class="token function">unlinkCancelledWaiters</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>interruptMode <span class="token operator">!=</span> <span class="token number">0</span><span class="token punctuation">)</span>
        <span class="token function">reportInterruptAfterWait</span><span class="token punctuation">(</span>interruptMode<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p> 添加条件队列节点</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">/**
 * Adds a new waiter to wait queue.
 * @return its new wait node
 */</span>
<span class="token keyword">private</span> <span class="token class-name">Node</span> <span class="token function">addConditionWaiter</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">Node</span> t <span class="token operator">=</span> lastWaiter<span class="token punctuation">;</span>
    <span class="token comment">// If lastWaiter is cancelled, clean out.</span>
    <span class="token comment">// 如果节点已经不是 CONDITION 状态了，表示已经取消了</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>t <span class="token operator">!=</span> <span class="token keyword">null</span> <span class="token operator">&amp;&amp;</span> t<span class="token punctuation">.</span>waitStatus <span class="token operator">!=</span> <span class="token class-name">Node</span><span class="token punctuation">.</span>CONDITION<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">// 把等待队列中取消的节点清理出去</span>
        <span class="token function">unlinkCancelledWaiters</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        t <span class="token operator">=</span> lastWaiter<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token comment">// 把当前线程包装成waitStatus=CONDITION 的节点</span>
    <span class="token class-name">Node</span> node <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Node</span><span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token class-name">Node</span><span class="token punctuation">.</span>CONDITION<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">// 没有 lastWaiter 节点，直接是 firstWaiter</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>t <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span>
        firstWaiter <span class="token operator">=</span> node<span class="token punctuation">;</span>
    <span class="token keyword">else</span>
    <span class="token comment">// 不然就接在 lastWaiter 后面</span>
        t<span class="token punctuation">.</span>nextWaiter <span class="token operator">=</span> node<span class="token punctuation">;</span>
    <span class="token comment">// 当前节点就会变成新的 lastWaiter</span>
    lastWaiter <span class="token operator">=</span> node<span class="token punctuation">;</span>
    <span class="token keyword">return</span> node<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>清理取消的节点</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">/**
 * Unlinks cancelled waiter nodes from condition queue.
 * Called only while holding lock. This is called when
 * cancellation occurred during condition wait, and upon
 * insertion of a new waiter when lastWaiter is seen to have
 * been cancelled. This method is needed to avoid garbage
 * retention in the absence of signals. So even though it may
 * require a full traversal, it comes into play only when
 * timeouts or cancellations occur in the absence of
 * signals. It traverses all nodes rather than stopping at a
 * particular target to unlink all pointers to garbage nodes
 * without requiring many re-traversals during cancellation
 * storms.
 */</span>
<span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">unlinkCancelledWaiters</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">Node</span> t <span class="token operator">=</span> firstWaiter<span class="token punctuation">;</span>
    <span class="token class-name">Node</span> trail <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
    <span class="token comment">// 循环遍历单向链表的节点，如果状态不是 CONDITION 就清出去</span>
    <span class="token keyword">while</span> <span class="token punctuation">(</span>t <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">Node</span> next <span class="token operator">=</span> t<span class="token punctuation">.</span>nextWaiter<span class="token punctuation">;</span>
        <span class="token comment">// 循环链表操作，清掉取消的节点</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>t<span class="token punctuation">.</span>waitStatus <span class="token operator">!=</span> <span class="token class-name">Node</span><span class="token punctuation">.</span>CONDITION<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            t<span class="token punctuation">.</span>nextWaiter <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>trail <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span>
                firstWaiter <span class="token operator">=</span> next<span class="token punctuation">;</span>
            <span class="token keyword">else</span>
                trail<span class="token punctuation">.</span>nextWaiter <span class="token operator">=</span> next<span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>next <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span>
                lastWaiter <span class="token operator">=</span> trail<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">else</span>
            trail <span class="token operator">=</span> t<span class="token punctuation">;</span>
        t <span class="token operator">=</span> next<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>完全释放锁</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">/**
 * Invokes release with current state value; returns saved state.
 * Cancels node and throws exception on failure.
 * @param node the condition node for this wait
 * @return previous sync state
 */</span>
<span class="token keyword">final</span> <span class="token keyword">int</span> <span class="token function">fullyRelease</span><span class="token punctuation">(</span><span class="token class-name">Node</span> node<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">boolean</span> failed <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
    <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">// 获取下当前的 state 值，因为是可重入的，所以这个值要保存下来</span>
        <span class="token keyword">int</span> savedState <span class="token operator">=</span> <span class="token function">getState</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">// 这里还包含比较多操作，不过跟前面分析 AQS 的释放比较类似，不深入了</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">release</span><span class="token punctuation">(</span>savedState<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            failed <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
            <span class="token comment">// 返回这个值</span>
            <span class="token keyword">return</span> savedState<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">IllegalMonitorStateException</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span> <span class="token keyword">finally</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>failed<span class="token punctuation">)</span>
            node<span class="token punctuation">.</span>waitStatus <span class="token operator">=</span> <span class="token class-name">Node</span><span class="token punctuation">.</span>CANCELLED<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>判断是否在阻塞队列中</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">/**
 * Returns true if a node, always one that was initially placed on
 * a condition queue, is now waiting to reacquire on sync queue.
 * @param node the node
 * @return true if is reacquiring
 */</span>
<span class="token keyword">final</span> <span class="token keyword">boolean</span> <span class="token function">isOnSyncQueue</span><span class="token punctuation">(</span><span class="token class-name">Node</span> node<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token comment">// 如果waitStatus 是 CONDITION 或者没有 prev 前置节点肯定就不在</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>node<span class="token punctuation">.</span>waitStatus <span class="token operator">==</span> <span class="token class-name">Node</span><span class="token punctuation">.</span>CONDITION <span class="token operator">||</span> node<span class="token punctuation">.</span>prev <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span>
        <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
    <span class="token comment">// 这里就是我前面提到的 next 的作用</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>node<span class="token punctuation">.</span>next <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token comment">// If has successor, it must be on queue</span>
        <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
    <span class="token comment">// 从 tail 开始找，是否在阻塞队列中</span>
    <span class="token comment">/*
     * node.prev can be non-null, but not yet on queue because
     * the CAS to place it on queue can fail. So we have to
     * traverse from tail to make sure it actually made it.  It
     * will always be near the tail in calls to this method, and
     * unless the CAS failed (which is unlikely), it will be
     * there, so we hardly ever traverse much.
     */</span>
    <span class="token keyword">return</span> <span class="token function">findNodeFromTail</span><span class="token punctuation">(</span>node<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">/**
 * Returns true if node is on sync queue by searching backwards from tail.
 * Called only when needed by isOnSyncQueue.
 * @return true if present
 */</span>
<span class="token keyword">private</span> <span class="token keyword">boolean</span> <span class="token function">findNodeFromTail</span><span class="token punctuation">(</span><span class="token class-name">Node</span> node<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">Node</span> t <span class="token operator">=</span> tail<span class="token punctuation">;</span>
    <span class="token comment">// 从 tail 开始，从后往前找</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token punctuation">;</span><span class="token punctuation">;</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>t <span class="token operator">==</span> node<span class="token punctuation">)</span>
            <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>t <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span>
            <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
        t <span class="token operator">=</span> t<span class="token punctuation">.</span>prev<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>await 的逻辑差不多就是这样子，主要的就是把自己包成一个 Node 节点，waitStatus 的状态是 CONDITION，挂在等待队列的最后，然后完全释放锁，park 等待</p>
<h2 id="signal"><a href="#signal" class="headerlink" title="signal"></a>signal</h2><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">/**
 * Moves the longest-waiting thread, if one exists, from the
 * wait queue for this condition to the wait queue for the
 * owning lock.
 *
 * @throws IllegalMonitorStateException if &#123;@link #isHeldExclusively&#125;
 *         returns &#123;@code false&#125;
 */</span>
<span class="token keyword">public</span> <span class="token keyword">final</span> <span class="token keyword">void</span> <span class="token function">signal</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token function">isHeldExclusively</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
        <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">IllegalMonitorStateException</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">// firstWaiter 肯定是最早开始等待的</span>
    <span class="token class-name">Node</span> first <span class="token operator">=</span> firstWaiter<span class="token punctuation">;</span>
    <span class="token comment">// 如果不为空就唤醒</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>first <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span>
        <span class="token function">doSignal</span><span class="token punctuation">(</span>first<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">/**
 * Removes and transfers nodes until hit non-cancelled one or
 * null. Split out from signal in part to encourage compilers
 * to inline the case of no waiters.
 * @param first (non-null) the first node on condition queue
 */</span>
<span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">doSignal</span><span class="token punctuation">(</span><span class="token class-name">Node</span> first<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">do</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">// 因为要去唤醒 first 节点了，firstWaiter 需要再从后面找一个</span>
        <span class="token comment">// 并且判断是否为空，如果是空的话就直接可以把 lastWaiter 设置成空了</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span> <span class="token punctuation">(</span>firstWaiter <span class="token operator">=</span> first<span class="token punctuation">.</span>nextWaiter<span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span>
            lastWaiter <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
        <span class="token comment">//  first 不需要继续保存后面的 waiter 了，因为 firstWaiter 已经是 first 的后置节点了</span>
        first<span class="token punctuation">.</span>nextWaiter <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
    <span class="token comment">// 如果 first 节点转移不成功，并且 firstWaiter 节点不为空，则继续进入循环</span>
    <span class="token punctuation">&#125;</span> <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token function">transferForSignal</span><span class="token punctuation">(</span>first<span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span>
             <span class="token punctuation">(</span>first <span class="token operator">=</span> firstWaiter<span class="token punctuation">)</span> <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">/**
 * Transfers a node from a condition queue onto sync queue.
 * Returns true if successful.
 * @param node the node
 * @return true if successfully transferred (else the node was
 * cancelled before signal)
 */</span>
<span class="token keyword">final</span> <span class="token keyword">boolean</span> <span class="token function">transferForSignal</span><span class="token punctuation">(</span><span class="token class-name">Node</span> node<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token comment">/*
     * If cannot change waitStatus, the node has been cancelled.
     */</span>
    <span class="token comment">// 如果状态已经不是 CONDITION 就不会设置成功，返回 false</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token function">compareAndSetWaitStatus</span><span class="token punctuation">(</span>node<span class="token punctuation">,</span> <span class="token class-name">Node</span><span class="token punctuation">.</span>CONDITION<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
        <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
    <span class="token comment">/*
     * Splice onto queue and try to set waitStatus of predecessor to
     * indicate that thread is (probably) waiting. If cancelled or
     * attempt to set waitStatus fails, wake up to resync (in which
     * case the waitStatus can be transiently and harmlessly wrong).
     */</span>
    <span class="token comment">// 调用跟aqs 第一篇中一样的 enq 方法进入阻塞队列，返回入队后的前一节点</span>
    <span class="token class-name">Node</span> p <span class="token operator">=</span> <span class="token function">enq</span><span class="token punctuation">(</span>node<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">int</span> ws <span class="token operator">=</span> p<span class="token punctuation">.</span>waitStatus<span class="token punctuation">;</span>
    <span class="token comment">// 将前置节点状态设置成SIGNAL，表示后面有节点在等了</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>ws <span class="token operator">></span> <span class="token number">0</span> <span class="token operator">||</span> <span class="token operator">!</span><span class="token function">compareAndSetWaitStatus</span><span class="token punctuation">(</span>p<span class="token punctuation">,</span> ws<span class="token punctuation">,</span> <span class="token class-name">Node</span><span class="token punctuation">.</span>SIGNAL<span class="token punctuation">)</span><span class="token punctuation">)</span>
        <span class="token class-name">LockSupport</span><span class="token punctuation">.</span><span class="token function">unpark</span><span class="token punctuation">(</span>node<span class="token punctuation">.</span>thread<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">// 返回 true，上一个方法的循环就退出了</span>
    <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这里其实就是把 condition 等待队列的第一个未取消的节点入队到阻塞队列去争锁</p>
<h2 id="附录"><a href="#附录" class="headerlink" title="附录"></a>附录</h2><p><code>synchronized</code> 版的 BoundedBuffer</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">/*
  File: BoundedBuffer.java

  Originally written by Doug Lea and released into the public domain.
  This may be used for any purposes whatsoever without acknowledgment.
  Thanks for the assistance and support of Sun Microsystems Labs,
  and everyone contributing, testing, and using this code.

  History:
  Date       Who                What
  11Jun1998  dl               Create public version
  17Jul1998  dl               Simplified by eliminating wait counts
  25aug1998  dl               added peek
   5May1999  dl               replace % with conditional (slightly faster)
*/</span>

<span class="token keyword">package</span> EDU<span class="token punctuation">.</span>oswego<span class="token punctuation">.</span>cs<span class="token punctuation">.</span>dl<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">;</span>

<span class="token comment">/**
 * Efficient array-based bounded buffer class.
 * Adapted from CPJ, chapter 8, which describes design.
 * &lt;p>[&lt;a href="http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html"> Introduction to this package. &lt;/a>] &lt;p>
 **/</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">BoundedBuffer</span> <span class="token keyword">implements</span> <span class="token class-name">BoundedChannel</span> <span class="token punctuation">&#123;</span>

  <span class="token keyword">protected</span> <span class="token keyword">final</span> <span class="token class-name">Object</span><span class="token punctuation">[</span><span class="token punctuation">]</span>  array_<span class="token punctuation">;</span>      <span class="token comment">// the elements</span>

  <span class="token keyword">protected</span> <span class="token keyword">int</span> takePtr_ <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>            <span class="token comment">// circular indices</span>
  <span class="token keyword">protected</span> <span class="token keyword">int</span> putPtr_ <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>       

  <span class="token keyword">protected</span> <span class="token keyword">int</span> usedSlots_ <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>          <span class="token comment">// length</span>
  <span class="token keyword">protected</span> <span class="token keyword">int</span> emptySlots_<span class="token punctuation">;</span>             <span class="token comment">// capacity - length</span>

  <span class="token comment">/**
   * Helper monitor to handle puts. 
   **/</span>
  <span class="token keyword">protected</span> <span class="token keyword">final</span> <span class="token class-name">Object</span> putMonitor_ <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Object</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token comment">/**
   * Create a BoundedBuffer with the given capacity.
   * @exception IllegalArgumentException if capacity less or equal to zero
   **/</span>
  <span class="token keyword">public</span> <span class="token class-name">BoundedBuffer</span><span class="token punctuation">(</span><span class="token keyword">int</span> capacity<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">IllegalArgumentException</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>capacity <span class="token operator">&lt;=</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">IllegalArgumentException</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    array_ <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Object</span><span class="token punctuation">[</span>capacity<span class="token punctuation">]</span><span class="token punctuation">;</span>
    emptySlots_ <span class="token operator">=</span> capacity<span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span>

  <span class="token comment">/**
   * Create a buffer with the current default capacity
   **/</span>

  <span class="token keyword">public</span> <span class="token class-name">BoundedBuffer</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span> 
    <span class="token keyword">this</span><span class="token punctuation">(</span><span class="token class-name">DefaultChannelCapacity</span><span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span> 
  <span class="token punctuation">&#125;</span>

  <span class="token comment">/** 
   * Return the number of elements in the buffer.
   * This is only a snapshot value, that may change
   * immediately after returning.
   **/</span>
  <span class="token keyword">public</span> <span class="token keyword">synchronized</span> <span class="token keyword">int</span> <span class="token function">size</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span> <span class="token keyword">return</span> usedSlots_<span class="token punctuation">;</span> <span class="token punctuation">&#125;</span>

  <span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">capacity</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span> <span class="token keyword">return</span> array_<span class="token punctuation">.</span>length<span class="token punctuation">;</span> <span class="token punctuation">&#125;</span>

  <span class="token keyword">protected</span> <span class="token keyword">void</span> <span class="token function">incEmptySlots</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">synchronized</span><span class="token punctuation">(</span>putMonitor_<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
      <span class="token operator">++</span>emptySlots_<span class="token punctuation">;</span>
      putMonitor_<span class="token punctuation">.</span><span class="token function">notify</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
  <span class="token punctuation">&#125;</span>

  <span class="token keyword">protected</span> <span class="token keyword">synchronized</span> <span class="token keyword">void</span> <span class="token function">incUsedSlots</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token operator">++</span>usedSlots_<span class="token punctuation">;</span>
    <span class="token function">notify</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span>

  <span class="token keyword">protected</span> <span class="token keyword">final</span> <span class="token keyword">void</span> <span class="token function">insert</span><span class="token punctuation">(</span><span class="token class-name">Object</span> x<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span> <span class="token comment">// mechanics of put</span>
    <span class="token operator">--</span>emptySlots_<span class="token punctuation">;</span>
    array_<span class="token punctuation">[</span>putPtr_<span class="token punctuation">]</span> <span class="token operator">=</span> x<span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">++</span>putPtr_ <span class="token operator">>=</span> array_<span class="token punctuation">.</span>length<span class="token punctuation">)</span> putPtr_ <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span>

  <span class="token keyword">protected</span> <span class="token keyword">final</span> <span class="token class-name">Object</span> <span class="token function">extract</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span> <span class="token comment">// mechanics of take</span>
    <span class="token operator">--</span>usedSlots_<span class="token punctuation">;</span>
    <span class="token class-name">Object</span> old <span class="token operator">=</span> array_<span class="token punctuation">[</span>takePtr_<span class="token punctuation">]</span><span class="token punctuation">;</span>
    array_<span class="token punctuation">[</span>takePtr_<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">++</span>takePtr_ <span class="token operator">>=</span> array_<span class="token punctuation">.</span>length<span class="token punctuation">)</span> takePtr_ <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> old<span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span>

  <span class="token keyword">public</span> <span class="token class-name">Object</span> <span class="token function">peek</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">synchronized</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
      <span class="token keyword">if</span> <span class="token punctuation">(</span>usedSlots_ <span class="token operator">></span> <span class="token number">0</span><span class="token punctuation">)</span>
        <span class="token keyword">return</span> array_<span class="token punctuation">[</span>takePtr_<span class="token punctuation">]</span><span class="token punctuation">;</span>
      <span class="token keyword">else</span>
        <span class="token keyword">return</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
  <span class="token punctuation">&#125;</span>


  <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">put</span><span class="token punctuation">(</span><span class="token class-name">Object</span> x<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>x <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">IllegalArgumentException</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">interrupted</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">InterruptedException</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">synchronized</span><span class="token punctuation">(</span>putMonitor_<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
      <span class="token keyword">while</span> <span class="token punctuation">(</span>emptySlots_ <span class="token operator">&lt;=</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">try</span> <span class="token punctuation">&#123;</span> putMonitor_<span class="token punctuation">.</span><span class="token function">wait</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">&#125;</span>
        <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> ex<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
          putMonitor_<span class="token punctuation">.</span><span class="token function">notify</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
          <span class="token keyword">throw</span> ex<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
      <span class="token punctuation">&#125;</span>
      <span class="token function">insert</span><span class="token punctuation">(</span>x<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token function">incUsedSlots</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span>

  <span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">offer</span><span class="token punctuation">(</span><span class="token class-name">Object</span> x<span class="token punctuation">,</span> <span class="token keyword">long</span> msecs<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>x <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">IllegalArgumentException</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">interrupted</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">InterruptedException</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">synchronized</span><span class="token punctuation">(</span>putMonitor_<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
      <span class="token keyword">long</span> start <span class="token operator">=</span> <span class="token punctuation">(</span>msecs <span class="token operator">&lt;=</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token operator">?</span> <span class="token number">0</span> <span class="token operator">:</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">currentTimeMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token keyword">long</span> waitTime <span class="token operator">=</span> msecs<span class="token punctuation">;</span>
      <span class="token keyword">while</span> <span class="token punctuation">(</span>emptySlots_ <span class="token operator">&lt;=</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>waitTime <span class="token operator">&lt;=</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
	<span class="token keyword">try</span> <span class="token punctuation">&#123;</span> putMonitor_<span class="token punctuation">.</span><span class="token function">wait</span><span class="token punctuation">(</span>waitTime<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">&#125;</span>
        <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> ex<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
          putMonitor_<span class="token punctuation">.</span><span class="token function">notify</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
          <span class="token keyword">throw</span> ex<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        waitTime <span class="token operator">=</span> msecs <span class="token operator">-</span> <span class="token punctuation">(</span><span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">currentTimeMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-</span> start<span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">&#125;</span>
      <span class="token function">insert</span><span class="token punctuation">(</span>x<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token function">incUsedSlots</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span>



  <span class="token keyword">public</span>  <span class="token class-name">Object</span> <span class="token function">take</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span> <span class="token punctuation">&#123;</span> 
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">interrupted</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">InterruptedException</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">Object</span> old <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span> 
    <span class="token keyword">synchronized</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span> 
      <span class="token keyword">while</span> <span class="token punctuation">(</span>usedSlots_ <span class="token operator">&lt;=</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">try</span> <span class="token punctuation">&#123;</span> <span class="token function">wait</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">&#125;</span>
        <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> ex<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
          <span class="token function">notify</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
          <span class="token keyword">throw</span> ex<span class="token punctuation">;</span> 
        <span class="token punctuation">&#125;</span>
      <span class="token punctuation">&#125;</span>
      old <span class="token operator">=</span> <span class="token function">extract</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token function">incEmptySlots</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> old<span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span>

  <span class="token keyword">public</span>  <span class="token class-name">Object</span> <span class="token function">poll</span><span class="token punctuation">(</span><span class="token keyword">long</span> msecs<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span> <span class="token punctuation">&#123;</span> 
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">interrupted</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">InterruptedException</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">Object</span> old <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span> 
    <span class="token keyword">synchronized</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span> 
      <span class="token keyword">long</span> start <span class="token operator">=</span> <span class="token punctuation">(</span>msecs <span class="token operator">&lt;=</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token operator">?</span> <span class="token number">0</span> <span class="token operator">:</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">currentTimeMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token keyword">long</span> waitTime <span class="token operator">=</span> msecs<span class="token punctuation">;</span>
      
      <span class="token keyword">while</span> <span class="token punctuation">(</span>usedSlots_ <span class="token operator">&lt;=</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>waitTime <span class="token operator">&lt;=</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token keyword">return</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
        <span class="token keyword">try</span> <span class="token punctuation">&#123;</span> <span class="token function">wait</span><span class="token punctuation">(</span>waitTime<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">&#125;</span>
        <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> ex<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
          <span class="token function">notify</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
          <span class="token keyword">throw</span> ex<span class="token punctuation">;</span> 
        <span class="token punctuation">&#125;</span>
        waitTime <span class="token operator">=</span> msecs <span class="token operator">-</span> <span class="token punctuation">(</span><span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">currentTimeMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-</span> start<span class="token punctuation">)</span><span class="token punctuation">;</span>

      <span class="token punctuation">&#125;</span>
      old <span class="token operator">=</span> <span class="token function">extract</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token function">incEmptySlots</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> old<span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span>

<span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
]]></content>
      <categories>
        <category>Java</category>
        <category>并发</category>
      </categories>
      <tags>
        <tag>java</tag>
        <tag>aqs</tag>
        <tag>并发</tag>
        <tag>j.u.c</tag>
        <tag>condition</tag>
        <tag>await</tag>
        <tag>signal</tag>
        <tag>lock</tag>
        <tag>unlock</tag>
      </tags>
  </entry>
  <entry>
    <title>Filter, Interceptor, Aop, 啥, 啥, 啥? 这些都是啥?</title>
    <url>/2020/08/22/Filter-Intercepter-Aop-%E5%95%A5-%E5%95%A5-%E5%95%A5-%E8%BF%99%E4%BA%9B%E9%83%BD%E6%98%AF%E5%95%A5/</url>
    <content><![CDATA[<p>本来是想取个像现在那些公众号转了又转的文章标题，”面试官再问你xxxxx，就把这篇文章甩给他看”这种标题，但是觉得实在太 low 了，还是用一部我比较喜欢的电影里的一句台词，《人在囧途》里王宝强对着那张老板给他的欠条，看不懂字时候说的那句，这些都是些啥（第四声）<br>当我刚开始面 Java 的时候，其实我真的没注意这方面的东西，实话说就是不知道这些是啥，开发中用过 Interceptor和 Aop，了解 aop 的实现原理，但是不知道 Java web 中的 Filter 是怎么回事，知道 dubbo 的 filter，就这样，所以被问到了的确是回答不出来，可能就觉得这个渣渣，这么简单的都不会，所以还是花点时间来看看这个是个啥，为了避免我口吐芬芳，还是耐下性子来简单说下这几个东西<br>首先是 servlet，怎么去解释这个呢，因为之前是 PHPer，所以比较喜欢用它来举例子，在普通的 PHP 的 web 应用中一般有几部分组成，接受 HTTP 请求的是前置的 nginx 或者 apache，但是这俩玩意都是只能处理静态的请求，远古时代 PHP 和 HTML 混编是通过 apache 的 php module，跟后来 nginx 使用 php-fpm 其实道理类似，就是把请求中需要 PHP 处理的转发给 PHP，在 Java 中呢，是有个比较牛叉的叫 Tomcat 的，它可以把请求转成 servlet，而 servlet 其实就是一种实现了特定接口的 Java 代码，</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">
<span class="token keyword">package</span> <span class="token namespace">javax<span class="token punctuation">.</span>servlet</span><span class="token punctuation">;</span>

<span class="token keyword">import</span> <span class="token namespace">java<span class="token punctuation">.</span>io<span class="token punctuation">.</span></span><span class="token class-name">IOException</span><span class="token punctuation">;</span>

<span class="token comment">/**
 * Defines methods that all servlets must implement.
 *
 * &lt;p>
 * A servlet is a small Java program that runs within a Web server. Servlets
 * receive and respond to requests from Web clients, usually across HTTP, the
 * HyperText Transfer Protocol.
 *
 * &lt;p>
 * To implement this interface, you can write a generic servlet that extends
 * &lt;code>javax.servlet.GenericServlet&lt;/code> or an HTTP servlet that extends
 * &lt;code>javax.servlet.http.HttpServlet&lt;/code>.
 *
 * &lt;p>
 * This interface defines methods to initialize a servlet, to service requests,
 * and to remove a servlet from the server. These are known as life-cycle
 * methods and are called in the following sequence:
 * &lt;ol>
 * &lt;li>The servlet is constructed, then initialized with the &lt;code>init&lt;/code>
 * method.
 * &lt;li>Any calls from clients to the &lt;code>service&lt;/code> method are handled.
 * &lt;li>The servlet is taken out of service, then destroyed with the
 * &lt;code>destroy&lt;/code> method, then garbage collected and finalized.
 * &lt;/ol>
 *
 * &lt;p>
 * In addition to the life-cycle methods, this interface provides the
 * &lt;code>getServletConfig&lt;/code> method, which the servlet can use to get any
 * startup information, and the &lt;code>getServletInfo&lt;/code> method, which allows
 * the servlet to return basic information about itself, such as author,
 * version, and copyright.
 *
 * @see GenericServlet
 * @see javax.servlet.http.HttpServlet
 */</span>
<span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">Servlet</span> <span class="token punctuation">&#123;</span>

    <span class="token comment">/**
     * Called by the servlet container to indicate to a servlet that the servlet
     * is being placed into service.
     *
     * &lt;p>
     * The servlet container calls the &lt;code>init&lt;/code> method exactly once
     * after instantiating the servlet. The &lt;code>init&lt;/code> method must
     * complete successfully before the servlet can receive any requests.
     *
     * &lt;p>
     * The servlet container cannot place the servlet into service if the
     * &lt;code>init&lt;/code> method
     * &lt;ol>
     * &lt;li>Throws a &lt;code>ServletException&lt;/code>
     * &lt;li>Does not return within a time period defined by the Web server
     * &lt;/ol>
     *
     *
     * @param config
     *            a &lt;code>ServletConfig&lt;/code> object containing the servlet's
     *            configuration and initialization parameters
     *
     * @exception ServletException
     *                if an exception has occurred that interferes with the
     *                servlet's normal operation
     *
     * @see UnavailableException
     * @see #getServletConfig
     */</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">init</span><span class="token punctuation">(</span><span class="token class-name">ServletConfig</span> config<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">ServletException</span><span class="token punctuation">;</span>

    <span class="token comment">/**
     *
     * Returns a &#123;@link ServletConfig&#125; object, which contains initialization and
     * startup parameters for this servlet. The &lt;code>ServletConfig&lt;/code>
     * object returned is the one passed to the &lt;code>init&lt;/code> method.
     *
     * &lt;p>
     * Implementations of this interface are responsible for storing the
     * &lt;code>ServletConfig&lt;/code> object so that this method can return it. The
     * &#123;@link GenericServlet&#125; class, which implements this interface, already
     * does this.
     *
     * @return the &lt;code>ServletConfig&lt;/code> object that initializes this
     *         servlet
     *
     * @see #init
     */</span>
    <span class="token keyword">public</span> <span class="token class-name">ServletConfig</span> <span class="token function">getServletConfig</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token comment">/**
     * Called by the servlet container to allow the servlet to respond to a
     * request.
     *
     * &lt;p>
     * This method is only called after the servlet's &lt;code>init()&lt;/code> method
     * has completed successfully.
     *
     * &lt;p>
     * The status code of the response always should be set for a servlet that
     * throws or sends an error.
     *
     *
     * &lt;p>
     * Servlets typically run inside multithreaded servlet containers that can
     * handle multiple requests concurrently. Developers must be aware to
     * synchronize access to any shared resources such as files, network
     * connections, and as well as the servlet's class and instance variables.
     * More information on multithreaded programming in Java is available in &lt;a
     * href
     * ="http://java.sun.com/Series/Tutorial/java/threads/multithreaded.html">
     * the Java tutorial on multi-threaded programming&lt;/a>.
     *
     *
     * @param req
     *            the &lt;code>ServletRequest&lt;/code> object that contains the
     *            client's request
     *
     * @param res
     *            the &lt;code>ServletResponse&lt;/code> object that contains the
     *            servlet's response
     *
     * @exception ServletException
     *                if an exception occurs that interferes with the servlet's
     *                normal operation
     *
     * @exception IOException
     *                if an input or output exception occurs
     */</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">service</span><span class="token punctuation">(</span><span class="token class-name">ServletRequest</span> req<span class="token punctuation">,</span> <span class="token class-name">ServletResponse</span> res<span class="token punctuation">)</span>
            <span class="token keyword">throws</span> <span class="token class-name">ServletException</span><span class="token punctuation">,</span> <span class="token class-name">IOException</span><span class="token punctuation">;</span>

    <span class="token comment">/**
     * Returns information about the servlet, such as author, version, and
     * copyright.
     *
     * &lt;p>
     * The string that this method returns should be plain text and not markup
     * of any kind (such as HTML, XML, etc.).
     *
     * @return a &lt;code>String&lt;/code> containing servlet information
     */</span>
    <span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">getServletInfo</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token comment">/**
     * Called by the servlet container to indicate to a servlet that the servlet
     * is being taken out of service. This method is only called once all
     * threads within the servlet's &lt;code>service&lt;/code> method have exited or
     * after a timeout period has passed. After the servlet container calls this
     * method, it will not call the &lt;code>service&lt;/code> method again on this
     * servlet.
     *
     * &lt;p>
     * This method gives the servlet an opportunity to clean up any resources
     * that are being held (for example, memory, file handles, threads) and make
     * sure that any persistent state is synchronized with the servlet's current
     * state in memory.
     */</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">destroy</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>重点看 servlet 的 service方法，就是接受请求，处理完了给响应，不说细节，不然光 Tomcat 的能说半年，所以呢再进一步去理解，其实就能知道，就是一个先后的问题，盗个图<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/2451842-a95c4ece9b4d3833.png"><br>filter 跟后两者最大的不一样其实是一个基于 servlet，在非常外层做的处理，然后是 interceptor 的 prehandle 跟 posthandle，接着才是我们常规的 aop，就这么点事情，做个小试验吧(还是先补段代码吧)</p>
<h2 id="Filter"><a href="#Filter" class="headerlink" title="Filter"></a>Filter</h2><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">// ---------------------------------------------------- FilterChain Methods</span>

    <span class="token comment">/**
     * Invoke the next filter in this chain, passing the specified request
     * and response.  If there are no more filters in this chain, invoke
     * the &lt;code>service()&lt;/code> method of the servlet itself.
     *
     * @param request The servlet request we are processing
     * @param response The servlet response we are creating
     *
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet exception occurs
     */</span>
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">doFilter</span><span class="token punctuation">(</span><span class="token class-name">ServletRequest</span> request<span class="token punctuation">,</span> <span class="token class-name">ServletResponse</span> response<span class="token punctuation">)</span>
        <span class="token keyword">throws</span> <span class="token class-name">IOException</span><span class="token punctuation">,</span> <span class="token class-name">ServletException</span> <span class="token punctuation">&#123;</span>

        <span class="token keyword">if</span><span class="token punctuation">(</span> <span class="token class-name">Globals</span><span class="token punctuation">.</span>IS_SECURITY_ENABLED <span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">final</span> <span class="token class-name">ServletRequest</span> req <span class="token operator">=</span> request<span class="token punctuation">;</span>
            <span class="token keyword">final</span> <span class="token class-name">ServletResponse</span> res <span class="token operator">=</span> response<span class="token punctuation">;</span>
            <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>security<span class="token punctuation">.</span></span>AccessController</span><span class="token punctuation">.</span><span class="token function">doPrivileged</span><span class="token punctuation">(</span>
                    <span class="token keyword">new</span> <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>security<span class="token punctuation">.</span></span>PrivilegedExceptionAction</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Void</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        <span class="token annotation punctuation">@Override</span>
                        <span class="token keyword">public</span> <span class="token class-name">Void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
                            <span class="token keyword">throws</span> <span class="token class-name">ServletException</span><span class="token punctuation">,</span> <span class="token class-name">IOException</span> <span class="token punctuation">&#123;</span>
                            <span class="token function">internalDoFilter</span><span class="token punctuation">(</span>req<span class="token punctuation">,</span>res<span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token keyword">return</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
                        <span class="token punctuation">&#125;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span><span class="token punctuation">(</span> <span class="token class-name">PrivilegedActionException</span> pe<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token class-name">Exception</span> e <span class="token operator">=</span> pe<span class="token punctuation">.</span><span class="token function">getException</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>e <span class="token keyword">instanceof</span> <span class="token class-name">ServletException</span><span class="token punctuation">)</span>
                    <span class="token keyword">throw</span> <span class="token punctuation">(</span><span class="token class-name">ServletException</span><span class="token punctuation">)</span> e<span class="token punctuation">;</span>
                <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>e <span class="token keyword">instanceof</span> <span class="token class-name">IOException</span><span class="token punctuation">)</span>
                    <span class="token keyword">throw</span> <span class="token punctuation">(</span><span class="token class-name">IOException</span><span class="token punctuation">)</span> e<span class="token punctuation">;</span>
                <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>e <span class="token keyword">instanceof</span> <span class="token class-name">RuntimeException</span><span class="token punctuation">)</span>
                    <span class="token keyword">throw</span> <span class="token punctuation">(</span><span class="token class-name">RuntimeException</span><span class="token punctuation">)</span> e<span class="token punctuation">;</span>
                <span class="token keyword">else</span>
                    <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">ServletException</span><span class="token punctuation">(</span>e<span class="token punctuation">.</span><span class="token function">getMessage</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
            <span class="token function">internalDoFilter</span><span class="token punctuation">(</span>request<span class="token punctuation">,</span>response<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">internalDoFilter</span><span class="token punctuation">(</span><span class="token class-name">ServletRequest</span> request<span class="token punctuation">,</span>
                                  <span class="token class-name">ServletResponse</span> response<span class="token punctuation">)</span>
        <span class="token keyword">throws</span> <span class="token class-name">IOException</span><span class="token punctuation">,</span> <span class="token class-name">ServletException</span> <span class="token punctuation">&#123;</span>

        <span class="token comment">// Call the next filter if there is one</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>pos <span class="token operator">&lt;</span> n<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">ApplicationFilterConfig</span> filterConfig <span class="token operator">=</span> filters<span class="token punctuation">[</span>pos<span class="token operator">++</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
            <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                <span class="token class-name">Filter</span> filter <span class="token operator">=</span> filterConfig<span class="token punctuation">.</span><span class="token function">getFilter</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

                <span class="token keyword">if</span> <span class="token punctuation">(</span>request<span class="token punctuation">.</span><span class="token function">isAsyncSupported</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> <span class="token string">"false"</span><span class="token punctuation">.</span><span class="token function">equalsIgnoreCase</span><span class="token punctuation">(</span>
                        filterConfig<span class="token punctuation">.</span><span class="token function">getFilterDef</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getAsyncSupported</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    request<span class="token punctuation">.</span><span class="token function">setAttribute</span><span class="token punctuation">(</span><span class="token class-name">Globals</span><span class="token punctuation">.</span>ASYNC_SUPPORTED_ATTR<span class="token punctuation">,</span> <span class="token class-name">Boolean</span><span class="token punctuation">.</span>FALSE<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
                <span class="token keyword">if</span><span class="token punctuation">(</span> <span class="token class-name">Globals</span><span class="token punctuation">.</span>IS_SECURITY_ENABLED <span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">final</span> <span class="token class-name">ServletRequest</span> req <span class="token operator">=</span> request<span class="token punctuation">;</span>
                    <span class="token keyword">final</span> <span class="token class-name">ServletResponse</span> res <span class="token operator">=</span> response<span class="token punctuation">;</span>
                    <span class="token class-name">Principal</span> principal <span class="token operator">=</span>
                        <span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token class-name">HttpServletRequest</span><span class="token punctuation">)</span> req<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getUserPrincipal</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

                    <span class="token class-name">Object</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Object</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">&#123;</span>req<span class="token punctuation">,</span> res<span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">&#125;</span><span class="token punctuation">;</span>
                    <span class="token class-name">SecurityUtil</span><span class="token punctuation">.</span>doAsPrivilege <span class="token punctuation">(</span><span class="token string">"doFilter"</span><span class="token punctuation">,</span> filter<span class="token punctuation">,</span> classType<span class="token punctuation">,</span> args<span class="token punctuation">,</span> principal<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                    filter<span class="token punctuation">.</span><span class="token function">doFilter</span><span class="token punctuation">(</span>request<span class="token punctuation">,</span> response<span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">IOException</span> <span class="token operator">|</span> <span class="token class-name">ServletException</span> <span class="token operator">|</span> <span class="token class-name">RuntimeException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">throw</span> e<span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Throwable</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                e <span class="token operator">=</span> <span class="token class-name">ExceptionUtils</span><span class="token punctuation">.</span><span class="token function">unwrapInvocationTargetException</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token class-name">ExceptionUtils</span><span class="token punctuation">.</span><span class="token function">handleThrowable</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">ServletException</span><span class="token punctuation">(</span>sm<span class="token punctuation">.</span><span class="token function">getString</span><span class="token punctuation">(</span><span class="token string">"filterChain.filter"</span><span class="token punctuation">)</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
            <span class="token keyword">return</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token comment">// We fell off the end of the chain -- call the servlet instance</span>
        <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">ApplicationDispatcher</span><span class="token punctuation">.</span>WRAP_SAME_OBJECT<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                lastServicedRequest<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span>request<span class="token punctuation">)</span><span class="token punctuation">;</span>
                lastServicedResponse<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span>response<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>

            <span class="token keyword">if</span> <span class="token punctuation">(</span>request<span class="token punctuation">.</span><span class="token function">isAsyncSupported</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> <span class="token operator">!</span>servletSupportsAsync<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                request<span class="token punctuation">.</span><span class="token function">setAttribute</span><span class="token punctuation">(</span><span class="token class-name">Globals</span><span class="token punctuation">.</span>ASYNC_SUPPORTED_ATTR<span class="token punctuation">,</span>
                        <span class="token class-name">Boolean</span><span class="token punctuation">.</span>FALSE<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
            <span class="token comment">// Use potentially wrapped request from this point</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token punctuation">(</span>request <span class="token keyword">instanceof</span> <span class="token class-name">HttpServletRequest</span><span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span>
                    <span class="token punctuation">(</span>response <span class="token keyword">instanceof</span> <span class="token class-name">HttpServletResponse</span><span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span>
                    <span class="token class-name">Globals</span><span class="token punctuation">.</span>IS_SECURITY_ENABLED <span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">final</span> <span class="token class-name">ServletRequest</span> req <span class="token operator">=</span> request<span class="token punctuation">;</span>
                <span class="token keyword">final</span> <span class="token class-name">ServletResponse</span> res <span class="token operator">=</span> response<span class="token punctuation">;</span>
                <span class="token class-name">Principal</span> principal <span class="token operator">=</span>
                    <span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token class-name">HttpServletRequest</span><span class="token punctuation">)</span> req<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getUserPrincipal</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token class-name">Object</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Object</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">&#123;</span>req<span class="token punctuation">,</span> res<span class="token punctuation">&#125;</span><span class="token punctuation">;</span>
                <span class="token class-name">SecurityUtil</span><span class="token punctuation">.</span><span class="token function">doAsPrivilege</span><span class="token punctuation">(</span><span class="token string">"service"</span><span class="token punctuation">,</span>
                                           servlet<span class="token punctuation">,</span>
                                           classTypeUsedInService<span class="token punctuation">,</span>
                                           args<span class="token punctuation">,</span>
                                           principal<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                servlet<span class="token punctuation">.</span><span class="token function">service</span><span class="token punctuation">(</span>request<span class="token punctuation">,</span> response<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">IOException</span> <span class="token operator">|</span> <span class="token class-name">ServletException</span> <span class="token operator">|</span> <span class="token class-name">RuntimeException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">throw</span> e<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Throwable</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            e <span class="token operator">=</span> <span class="token class-name">ExceptionUtils</span><span class="token punctuation">.</span><span class="token function">unwrapInvocationTargetException</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">ExceptionUtils</span><span class="token punctuation">.</span><span class="token function">handleThrowable</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">ServletException</span><span class="token punctuation">(</span>sm<span class="token punctuation">.</span><span class="token function">getString</span><span class="token punctuation">(</span><span class="token string">"filterChain.servlet"</span><span class="token punctuation">)</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">finally</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">ApplicationDispatcher</span><span class="token punctuation">.</span>WRAP_SAME_OBJECT<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                lastServicedRequest<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                lastServicedResponse<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>注意看这一行<br><code>filter.doFilter(request, response, this);</code><br>是不是看懂了，就是个 filter 链，但是这个代码在哪呢，<code>org.apache.catalina.core.ApplicationFilterChain#doFilter</code><br>然后是interceptor，</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">protected</span> <span class="token keyword">void</span> <span class="token function">doDispatch</span><span class="token punctuation">(</span><span class="token class-name">HttpServletRequest</span> request<span class="token punctuation">,</span> <span class="token class-name">HttpServletResponse</span> response<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">Exception</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">HttpServletRequest</span> processedRequest <span class="token operator">=</span> request<span class="token punctuation">;</span>
        <span class="token class-name">HandlerExecutionChain</span> mappedHandler <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
        <span class="token keyword">boolean</span> multipartRequestParsed <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
        <span class="token class-name">WebAsyncManager</span> asyncManager <span class="token operator">=</span> <span class="token class-name">WebAsyncUtils</span><span class="token punctuation">.</span><span class="token function">getAsyncManager</span><span class="token punctuation">(</span>request<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                <span class="token class-name">ModelAndView</span> mv <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
                <span class="token class-name">Object</span> dispatchException <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>

                <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                    processedRequest <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">checkMultipart</span><span class="token punctuation">(</span>request<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    multipartRequestParsed <span class="token operator">=</span> processedRequest <span class="token operator">!=</span> request<span class="token punctuation">;</span>
                    mappedHandler <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getHandler</span><span class="token punctuation">(</span>processedRequest<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">if</span> <span class="token punctuation">(</span>mappedHandler <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">noHandlerFound</span><span class="token punctuation">(</span>processedRequest<span class="token punctuation">,</span> response<span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token keyword">return</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>

                    <span class="token class-name">HandlerAdapter</span> ha <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getHandlerAdapter</span><span class="token punctuation">(</span>mappedHandler<span class="token punctuation">.</span><span class="token function">getHandler</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token class-name">String</span> method <span class="token operator">=</span> request<span class="token punctuation">.</span><span class="token function">getMethod</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">boolean</span> isGet <span class="token operator">=</span> <span class="token string">"GET"</span><span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>method<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">if</span> <span class="token punctuation">(</span>isGet <span class="token operator">||</span> <span class="token string">"HEAD"</span><span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>method<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        <span class="token keyword">long</span> lastModified <span class="token operator">=</span> ha<span class="token punctuation">.</span><span class="token function">getLastModified</span><span class="token punctuation">(</span>request<span class="token punctuation">,</span> mappedHandler<span class="token punctuation">.</span><span class="token function">getHandler</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">ServletWebRequest</span><span class="token punctuation">(</span>request<span class="token punctuation">,</span> response<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">checkNotModified</span><span class="token punctuation">(</span>lastModified<span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> isGet<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                            <span class="token keyword">return</span><span class="token punctuation">;</span>
                        <span class="token punctuation">&#125;</span>
                    <span class="token punctuation">&#125;</span>

                    <span class="token comment">/** 
                     * 看这里看这里‼️
                     */</span>
                    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>mappedHandler<span class="token punctuation">.</span><span class="token function">applyPreHandle</span><span class="token punctuation">(</span>processedRequest<span class="token punctuation">,</span> response<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        <span class="token keyword">return</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>

                    mv <span class="token operator">=</span> ha<span class="token punctuation">.</span><span class="token function">handle</span><span class="token punctuation">(</span>processedRequest<span class="token punctuation">,</span> response<span class="token punctuation">,</span> mappedHandler<span class="token punctuation">.</span><span class="token function">getHandler</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">if</span> <span class="token punctuation">(</span>asyncManager<span class="token punctuation">.</span><span class="token function">isConcurrentHandlingStarted</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        <span class="token keyword">return</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>

                    <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">applyDefaultViewName</span><span class="token punctuation">(</span>processedRequest<span class="token punctuation">,</span> mv<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token comment">/** 
                     * 再看这里看这里‼️
                     */</span>
                    mappedHandler<span class="token punctuation">.</span><span class="token function">applyPostHandle</span><span class="token punctuation">(</span>processedRequest<span class="token punctuation">,</span> response<span class="token punctuation">,</span> mv<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> var20<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    dispatchException <span class="token operator">=</span> var20<span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Throwable</span> var21<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    dispatchException <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">NestedServletException</span><span class="token punctuation">(</span><span class="token string">"Handler dispatch failed"</span><span class="token punctuation">,</span> var21<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>

                <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">processDispatchResult</span><span class="token punctuation">(</span>processedRequest<span class="token punctuation">,</span> response<span class="token punctuation">,</span> mappedHandler<span class="token punctuation">,</span> mv<span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span><span class="token punctuation">)</span>dispatchException<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> var22<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">triggerAfterCompletion</span><span class="token punctuation">(</span>processedRequest<span class="token punctuation">,</span> response<span class="token punctuation">,</span> mappedHandler<span class="token punctuation">,</span> var22<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Throwable</span> var23<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">triggerAfterCompletion</span><span class="token punctuation">(</span>processedRequest<span class="token punctuation">,</span> response<span class="token punctuation">,</span> mappedHandler<span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">NestedServletException</span><span class="token punctuation">(</span><span class="token string">"Handler processing failed"</span><span class="token punctuation">,</span> var23<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>

        <span class="token punctuation">&#125;</span> <span class="token keyword">finally</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>asyncManager<span class="token punctuation">.</span><span class="token function">isConcurrentHandlingStarted</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>mappedHandler <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    mappedHandler<span class="token punctuation">.</span><span class="token function">applyAfterConcurrentHandlingStarted</span><span class="token punctuation">(</span>processedRequest<span class="token punctuation">,</span> response<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>multipartRequestParsed<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">cleanupMultipart</span><span class="token punctuation">(</span>processedRequest<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>

        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>代码在哪呢，<code>org.springframework.web.servlet.DispatcherServlet#doDispatch</code>，然后才是我们自己写的 aop，是不是差不多明白了，嗯，接下来是例子<br>写个 filter</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">DemoFilter</span> <span class="token keyword">extends</span> <span class="token class-name">HttpServlet</span> <span class="token keyword">implements</span> <span class="token class-name">Filter</span> <span class="token punctuation">&#123;</span>
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">init</span><span class="token punctuation">(</span><span class="token class-name">FilterConfig</span> filterConfig<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">ServletException</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"==>DemoFilter启动"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">doFilter</span><span class="token punctuation">(</span><span class="token class-name">ServletRequest</span> servletRequest<span class="token punctuation">,</span> <span class="token class-name">ServletResponse</span> servletResponse<span class="token punctuation">,</span> <span class="token class-name">FilterChain</span> filterChain<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">IOException</span><span class="token punctuation">,</span> <span class="token class-name">ServletException</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">// 将请求转换成HttpServletRequest 请求</span>
        <span class="token class-name">HttpServletRequest</span> req <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">HttpServletRequest</span><span class="token punctuation">)</span> servletRequest<span class="token punctuation">;</span>
        <span class="token class-name">HttpServletResponse</span> resp <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">HttpServletResponse</span><span class="token punctuation">)</span> servletResponse<span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"before filter"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        filterChain<span class="token punctuation">.</span><span class="token function">doFilter</span><span class="token punctuation">(</span>req<span class="token punctuation">,</span> resp<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"after filter"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">destroy</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>

    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>因为用的springboot，所以就不写 web.xml 了，写个配置类</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Configuration</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">FilterConfiguration</span> <span class="token punctuation">&#123;</span>
    <span class="token annotation punctuation">@Bean</span>
    <span class="token keyword">public</span> <span class="token class-name">FilterRegistrationBean</span> <span class="token function">filterDemo4Registration</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">FilterRegistrationBean</span> registration <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">FilterRegistrationBean</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">//注入过滤器</span>
        registration<span class="token punctuation">.</span><span class="token function">setFilter</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">DemoFilter</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">//拦截规则</span>
        registration<span class="token punctuation">.</span><span class="token function">addUrlPatterns</span><span class="token punctuation">(</span><span class="token string">"/*"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">//过滤器名称</span>
        registration<span class="token punctuation">.</span><span class="token function">setName</span><span class="token punctuation">(</span><span class="token string">"DemoFilter"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">//是否自动注册 false 取消Filter的自动注册</span>
        registration<span class="token punctuation">.</span><span class="token function">setEnabled</span><span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">//过滤器顺序</span>
        registration<span class="token punctuation">.</span><span class="token function">setOrder</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> registration<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>然后再来个 interceptor 和 aop,以及一个简单的请求处理</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">DemoInterceptor</span> <span class="token keyword">extends</span> <span class="token class-name">HandlerInterceptorAdapter</span> <span class="token punctuation">&#123;</span>
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">preHandle</span><span class="token punctuation">(</span><span class="token class-name">HttpServletRequest</span> request<span class="token punctuation">,</span> <span class="token class-name">HttpServletResponse</span> response<span class="token punctuation">,</span> <span class="token class-name">Object</span> handler<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">Exception</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"preHandle test"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">postHandle</span><span class="token punctuation">(</span><span class="token class-name">HttpServletRequest</span> request<span class="token punctuation">,</span> <span class="token class-name">HttpServletResponse</span> response<span class="token punctuation">,</span> <span class="token class-name">Object</span> handler<span class="token punctuation">,</span> <span class="token class-name">ModelAndView</span> modelAndView<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">Exception</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"postHandle test"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>
<span class="token annotation punctuation">@Aspect</span>
<span class="token annotation punctuation">@Component</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">DemoAspect</span> <span class="token punctuation">&#123;</span>

    <span class="token annotation punctuation">@Pointcut</span><span class="token punctuation">(</span><span class="token string">"execution( public * com.nicksxs.springbootdemo.demo.DemoController.*())"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">point</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>

    <span class="token punctuation">&#125;</span>

    <span class="token annotation punctuation">@Before</span><span class="token punctuation">(</span><span class="token string">"point()"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">doBefore</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"==doBefore=="</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token annotation punctuation">@After</span><span class="token punctuation">(</span><span class="token string">"point()"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">doAfter</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"==doAfter=="</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>
<span class="token annotation punctuation">@RestController</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">DemoController</span> <span class="token punctuation">&#123;</span>

    <span class="token annotation punctuation">@RequestMapping</span><span class="token punctuation">(</span><span class="token string">"/hello"</span><span class="token punctuation">)</span>
    <span class="token annotation punctuation">@ResponseBody</span>
    <span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">hello</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> <span class="token string">"hello world"</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>好了，请求一下，看看 stdout，<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/pT4oXL.png"><br>搞定完事儿~</p>
]]></content>
      <categories>
        <category>Java</category>
        <category>Spring</category>
        <category>Filter</category>
        <category>Interceptor - AOP</category>
        <category>Servlet</category>
        <category>Interceptor</category>
        <category>AOP</category>
      </categories>
      <tags>
        <tag>Java</tag>
        <tag>Spring</tag>
        <tag>Filter</tag>
        <tag>Interceptor</tag>
        <tag>AOP</tag>
        <tag>Tomcat</tag>
        <tag>Servlet</tag>
        <tag>Web</tag>
      </tags>
  </entry>
  <entry>
    <title>JVM源码分析之G1垃圾收集器分析一</title>
    <url>/2019/12/07/JVM-G1-Part-1/</url>
    <content><![CDATA[<p>对 Java 的 gc 实现比较感兴趣，原先一般都是看周志明的书，但其实并没有讲具体的 gc 源码，而是把整个思路和流程讲解了一下<br>特别是 G1 的具体实现<br>一般对 G1 的理解其实就是把原先整块的新生代老年代分成了以 region 为单位的小块内存，简而言之，就是原先对新生代老年代的收集会涉及到整个代的堆内存空间，而G1 把它变成了更细致的小块内存<br>这带来了一个很明显的好处和一个很明显的坏处，好处是内存收集可以更灵活，耗时会变短，但整个收集的处理复杂度就变高了<br>目前看了一点点关于 G1 收集的预期时间相关的代码</p>
<pre class="line-numbers language-C++" data-language="C++"><code class="language-C++">HeapWord* G1CollectedHeap::do_collection_pause(size_t word_size,
                                               uint gc_count_before,
                                               bool* succeeded,
                                               GCCause::Cause gc_cause) &#123;
  assert_heap_not_locked_and_not_at_safepoint();
  VM_G1CollectForAllocation op(word_size,
                               gc_count_before,
                               gc_cause,
                               false, &#x2F;* should_initiate_conc_mark *&#x2F;
                               g1_policy()-&gt;max_pause_time_ms());
  VMThread::execute(&amp;op);

  HeapWord* result &#x3D; op.result();
  bool ret_succeeded &#x3D; op.prologue_succeeded() &amp;&amp; op.pause_succeeded();
  assert(result &#x3D;&#x3D; NULL || ret_succeeded,
         &quot;the result should be NULL if the VM did not succeed&quot;);
  *succeeded &#x3D; ret_succeeded;

  assert_heap_not_locked();
  return result;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这里就是收集时需要停顿的，其中<code>VMThread::execute(&amp;op);</code>是具体执行的，真正执行的是<code>VM_G1CollectForAllocation::doit</code>方法</p>
<pre class="line-numbers language-C++" data-language="C++"><code class="language-C++">void VM_G1CollectForAllocation::doit() &#123;
  G1CollectedHeap* g1h &#x3D; G1CollectedHeap::heap();
  assert(!_should_initiate_conc_mark || g1h-&gt;should_do_concurrent_full_gc(_gc_cause),
      &quot;only a GC locker, a System.gc(), stats update, whitebox, or a hum allocation induced GC should start a cycle&quot;);

  if (_word_size &gt; 0) &#123;
    &#x2F;&#x2F; An allocation has been requested. So, try to do that first.
    _result &#x3D; g1h-&gt;attempt_allocation_at_safepoint(_word_size,
                                                   false &#x2F;* expect_null_cur_alloc_region *&#x2F;);
    if (_result !&#x3D; NULL) &#123;
      &#x2F;&#x2F; If we can successfully allocate before we actually do the
      &#x2F;&#x2F; pause then we will consider this pause successful.
      _pause_succeeded &#x3D; true;
      return;
    &#125;
  &#125;

  GCCauseSetter x(g1h, _gc_cause);
  if (_should_initiate_conc_mark) &#123;
    &#x2F;&#x2F; It&#39;s safer to read old_marking_cycles_completed() here, given
    &#x2F;&#x2F; that noone else will be updating it concurrently. Since we&#39;ll
    &#x2F;&#x2F; only need it if we&#39;re initiating a marking cycle, no point in
    &#x2F;&#x2F; setting it earlier.
    _old_marking_cycles_completed_before &#x3D; g1h-&gt;old_marking_cycles_completed();

    &#x2F;&#x2F; At this point we are supposed to start a concurrent cycle. We
    &#x2F;&#x2F; will do so if one is not already in progress.
    bool res &#x3D; g1h-&gt;g1_policy()-&gt;force_initial_mark_if_outside_cycle(_gc_cause);

    &#x2F;&#x2F; The above routine returns true if we were able to force the
    &#x2F;&#x2F; next GC pause to be an initial mark; it returns false if a
    &#x2F;&#x2F; marking cycle is already in progress.
    &#x2F;&#x2F;
    &#x2F;&#x2F; If a marking cycle is already in progress just return and skip the
    &#x2F;&#x2F; pause below - if the reason for requesting this initial mark pause
    &#x2F;&#x2F; was due to a System.gc() then the requesting thread should block in
    &#x2F;&#x2F; doit_epilogue() until the marking cycle is complete.
    &#x2F;&#x2F;
    &#x2F;&#x2F; If this initial mark pause was requested as part of a humongous
    &#x2F;&#x2F; allocation then we know that the marking cycle must just have
    &#x2F;&#x2F; been started by another thread (possibly also allocating a humongous
    &#x2F;&#x2F; object) as there was no active marking cycle when the requesting
    &#x2F;&#x2F; thread checked before calling collect() in
    &#x2F;&#x2F; attempt_allocation_humongous(). Retrying the GC, in this case,
    &#x2F;&#x2F; will cause the requesting thread to spin inside collect() until the
    &#x2F;&#x2F; just started marking cycle is complete - which may be a while. So
    &#x2F;&#x2F; we do NOT retry the GC.
    if (!res) &#123;
      assert(_word_size &#x3D;&#x3D; 0, &quot;Concurrent Full GC&#x2F;Humongous Object IM shouldn&#39;t be allocating&quot;);
      if (_gc_cause !&#x3D; GCCause::_g1_humongous_allocation) &#123;
        _should_retry_gc &#x3D; true;
      &#125;
      return;
    &#125;
  &#125;

  &#x2F;&#x2F; Try a partial collection of some kind.
  _pause_succeeded &#x3D; g1h-&gt;do_collection_pause_at_safepoint(_target_pause_time_ms);

  if (_pause_succeeded) &#123;
    if (_word_size &gt; 0) &#123;
      &#x2F;&#x2F; An allocation had been requested. Do it, eventually trying a stronger
      &#x2F;&#x2F; kind of GC.
      _result &#x3D; g1h-&gt;satisfy_failed_allocation(_word_size, &amp;_pause_succeeded);
    &#125; else &#123;
      bool should_upgrade_to_full &#x3D; !g1h-&gt;should_do_concurrent_full_gc(_gc_cause) &amp;&amp;
                                    !g1h-&gt;has_regions_left_for_allocation();
      if (should_upgrade_to_full) &#123;
        &#x2F;&#x2F; There has been a request to perform a GC to free some space. We have no
        &#x2F;&#x2F; information on how much memory has been asked for. In case there are
        &#x2F;&#x2F; absolutely no regions left to allocate into, do a maximally compacting full GC.
        log_info(gc, ergo)(&quot;Attempting maximally compacting collection&quot;);
        _pause_succeeded &#x3D; g1h-&gt;do_full_collection(false, &#x2F;* explicit gc *&#x2F;
                                                   true   &#x2F;* clear_all_soft_refs *&#x2F;);
      &#125;
    &#125;
    guarantee(_pause_succeeded, &quot;Elevated collections during the safepoint must always succeed.&quot;);
  &#125; else &#123;
    assert(_result &#x3D;&#x3D; NULL, &quot;invariant&quot;);
    &#x2F;&#x2F; The only reason for the pause to not be successful is that, the GC locker is
    &#x2F;&#x2F; active (or has become active since the prologue was executed). In this case
    &#x2F;&#x2F; we should retry the pause after waiting for the GC locker to become inactive.
    _should_retry_gc &#x3D; true;
  &#125;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这里可以看到核心的是<code>G1CollectedHeap::do_collection_pause_at_safepoint</code>这个方法，它带上了目标暂停时间的值</p>
<pre class="line-numbers language-C++" data-language="C++"><code class="language-C++">G1CollectedHeap::do_collection_pause_at_safepoint(double target_pause_time_ms) &#123;
  assert_at_safepoint_on_vm_thread();
  guarantee(!is_gc_active(), &quot;collection is not reentrant&quot;);

  if (GCLocker::check_active_before_gc()) &#123;
    return false;
  &#125;

  _gc_timer_stw-&gt;register_gc_start();

  GCIdMark gc_id_mark;
  _gc_tracer_stw-&gt;report_gc_start(gc_cause(), _gc_timer_stw-&gt;gc_start());

  SvcGCMarker sgcm(SvcGCMarker::MINOR);
  ResourceMark rm;

  g1_policy()-&gt;note_gc_start();

  wait_for_root_region_scanning();

  print_heap_before_gc();
  print_heap_regions();
  trace_heap_before_gc(_gc_tracer_stw);

  _verifier-&gt;verify_region_sets_optional();
  _verifier-&gt;verify_dirty_young_regions();

  &#x2F;&#x2F; We should not be doing initial mark unless the conc mark thread is running
  if (!_cm_thread-&gt;should_terminate()) &#123;
    &#x2F;&#x2F; This call will decide whether this pause is an initial-mark
    &#x2F;&#x2F; pause. If it is, in_initial_mark_gc() will return true
    &#x2F;&#x2F; for the duration of this pause.
    g1_policy()-&gt;decide_on_conc_mark_initiation();
  &#125;

  &#x2F;&#x2F; We do not allow initial-mark to be piggy-backed on a mixed GC.
  assert(!collector_state()-&gt;in_initial_mark_gc() ||
          collector_state()-&gt;in_young_only_phase(), &quot;sanity&quot;);

  &#x2F;&#x2F; We also do not allow mixed GCs during marking.
  assert(!collector_state()-&gt;mark_or_rebuild_in_progress() || collector_state()-&gt;in_young_only_phase(), &quot;sanity&quot;);

  &#x2F;&#x2F; Record whether this pause is an initial mark. When the current
  &#x2F;&#x2F; thread has completed its logging output and it&#39;s safe to signal
  &#x2F;&#x2F; the CM thread, the flag&#39;s value in the policy has been reset.
  bool should_start_conc_mark &#x3D; collector_state()-&gt;in_initial_mark_gc();

  &#x2F;&#x2F; Inner scope for scope based logging, timers, and stats collection
  &#123;
    EvacuationInfo evacuation_info;

    if (collector_state()-&gt;in_initial_mark_gc()) &#123;
      &#x2F;&#x2F; We are about to start a marking cycle, so we increment the
      &#x2F;&#x2F; full collection counter.
      increment_old_marking_cycles_started();
      _cm-&gt;gc_tracer_cm()-&gt;set_gc_cause(gc_cause());
    &#125;

    _gc_tracer_stw-&gt;report_yc_type(collector_state()-&gt;yc_type());

    GCTraceCPUTime tcpu;

    G1HeapVerifier::G1VerifyType verify_type;
    FormatBuffer&lt;&gt; gc_string(&quot;Pause Young &quot;);
    if (collector_state()-&gt;in_initial_mark_gc()) &#123;
      gc_string.append(&quot;(Concurrent Start)&quot;);
      verify_type &#x3D; G1HeapVerifier::G1VerifyConcurrentStart;
    &#125; else if (collector_state()-&gt;in_young_only_phase()) &#123;
      if (collector_state()-&gt;in_young_gc_before_mixed()) &#123;
        gc_string.append(&quot;(Prepare Mixed)&quot;);
      &#125; else &#123;
        gc_string.append(&quot;(Normal)&quot;);
      &#125;
      verify_type &#x3D; G1HeapVerifier::G1VerifyYoungNormal;
    &#125; else &#123;
      gc_string.append(&quot;(Mixed)&quot;);
      verify_type &#x3D; G1HeapVerifier::G1VerifyMixed;
    &#125;
    GCTraceTime(Info, gc) tm(gc_string, NULL, gc_cause(), true);

    uint active_workers &#x3D; AdaptiveSizePolicy::calc_active_workers(workers()-&gt;total_workers(),
                                                                  workers()-&gt;active_workers(),
                                                                  Threads::number_of_non_daemon_threads());
    active_workers &#x3D; workers()-&gt;update_active_workers(active_workers);
    log_info(gc,task)(&quot;Using %u workers of %u for evacuation&quot;, active_workers, workers()-&gt;total_workers());

    TraceCollectorStats tcs(g1mm()-&gt;incremental_collection_counters());
    TraceMemoryManagerStats tms(&amp;_memory_manager, gc_cause(),
                                collector_state()-&gt;yc_type() &#x3D;&#x3D; Mixed &#x2F;* allMemoryPoolsAffected *&#x2F;);

    G1HeapTransition heap_transition(this);
    size_t heap_used_bytes_before_gc &#x3D; used();

    &#x2F;&#x2F; Don&#39;t dynamically change the number of GC threads this early.  A value of
    &#x2F;&#x2F; 0 is used to indicate serial work.  When parallel work is done,
    &#x2F;&#x2F; it will be set.

    &#123; &#x2F;&#x2F; Call to jvmpi::post_class_unload_events must occur outside of active GC
      IsGCActiveMark x;

      gc_prologue(false);

      if (VerifyRememberedSets) &#123;
        log_info(gc, verify)(&quot;[Verifying RemSets before GC]&quot;);
        VerifyRegionRemSetClosure v_cl;
        heap_region_iterate(&amp;v_cl);
      &#125;

      _verifier-&gt;verify_before_gc(verify_type);

      _verifier-&gt;check_bitmaps(&quot;GC Start&quot;);

#if COMPILER2_OR_JVMCI
      DerivedPointerTable::clear();
#endif

      &#x2F;&#x2F; Please see comment in g1CollectedHeap.hpp and
      &#x2F;&#x2F; G1CollectedHeap::ref_processing_init() to see how
      &#x2F;&#x2F; reference processing currently works in G1.

      &#x2F;&#x2F; Enable discovery in the STW reference processor
      _ref_processor_stw-&gt;enable_discovery();

      &#123;
        &#x2F;&#x2F; We want to temporarily turn off discovery by the
        &#x2F;&#x2F; CM ref processor, if necessary, and turn it back on
        &#x2F;&#x2F; on again later if we do. Using a scoped
        &#x2F;&#x2F; NoRefDiscovery object will do this.
        NoRefDiscovery no_cm_discovery(_ref_processor_cm);

        &#x2F;&#x2F; Forget the current alloc region (we might even choose it to be part
        &#x2F;&#x2F; of the collection set!).
        _allocator-&gt;release_mutator_alloc_region();

        &#x2F;&#x2F; This timing is only used by the ergonomics to handle our pause target.
        &#x2F;&#x2F; It is unclear why this should not include the full pause. We will
        &#x2F;&#x2F; investigate this in CR 7178365.
        &#x2F;&#x2F;
        &#x2F;&#x2F; Preserving the old comment here if that helps the investigation:
        &#x2F;&#x2F;
        &#x2F;&#x2F; The elapsed time induced by the start time below deliberately elides
        &#x2F;&#x2F; the possible verification above.
        double sample_start_time_sec &#x3D; os::elapsedTime();

        g1_policy()-&gt;record_collection_pause_start(sample_start_time_sec);

        if (collector_state()-&gt;in_initial_mark_gc()) &#123;
          concurrent_mark()-&gt;pre_initial_mark();
        &#125;

        g1_policy()-&gt;finalize_collection_set(target_pause_time_ms, &amp;_survivor);

        evacuation_info.set_collectionset_regions(collection_set()-&gt;region_length());

        &#x2F;&#x2F; Make sure the remembered sets are up to date. This needs to be
        &#x2F;&#x2F; done before register_humongous_regions_with_cset(), because the
        &#x2F;&#x2F; remembered sets are used there to choose eager reclaim candidates.
        &#x2F;&#x2F; If the remembered sets are not up to date we might miss some
        &#x2F;&#x2F; entries that need to be handled.
        g1_rem_set()-&gt;cleanupHRRS();

        register_humongous_regions_with_cset();

        assert(_verifier-&gt;check_cset_fast_test(), &quot;Inconsistency in the InCSetState table.&quot;);

        &#x2F;&#x2F; We call this after finalize_cset() to
        &#x2F;&#x2F; ensure that the CSet has been finalized.
        _cm-&gt;verify_no_cset_oops();

        if (_hr_printer.is_active()) &#123;
          G1PrintCollectionSetClosure cl(&amp;_hr_printer);
          _collection_set.iterate(&amp;cl);
        &#125;

        &#x2F;&#x2F; Initialize the GC alloc regions.
        _allocator-&gt;init_gc_alloc_regions(evacuation_info);

        G1ParScanThreadStateSet per_thread_states(this, workers()-&gt;active_workers(), collection_set()-&gt;young_region_length());
        pre_evacuate_collection_set();

        &#x2F;&#x2F; Actually do the work...
        evacuate_collection_set(&amp;per_thread_states);

        post_evacuate_collection_set(evacuation_info, &amp;per_thread_states);

        const size_t* surviving_young_words &#x3D; per_thread_states.surviving_young_words();
        free_collection_set(&amp;_collection_set, evacuation_info, surviving_young_words);

        eagerly_reclaim_humongous_regions();

        record_obj_copy_mem_stats();
        _survivor_evac_stats.adjust_desired_plab_sz();
        _old_evac_stats.adjust_desired_plab_sz();

        double start &#x3D; os::elapsedTime();
        start_new_collection_set();
        g1_policy()-&gt;phase_times()-&gt;record_start_new_cset_time_ms((os::elapsedTime() - start) * 1000.0);

        if (evacuation_failed()) &#123;
          set_used(recalculate_used());
          if (_archive_allocator !&#x3D; NULL) &#123;
            _archive_allocator-&gt;clear_used();
          &#125;
          for (uint i &#x3D; 0; i &lt; ParallelGCThreads; i++) &#123;
            if (_evacuation_failed_info_array[i].has_failed()) &#123;
              _gc_tracer_stw-&gt;report_evacuation_failed(_evacuation_failed_info_array[i]);
            &#125;
          &#125;
        &#125; else &#123;
          &#x2F;&#x2F; The &quot;used&quot; of the the collection set have already been subtracted
          &#x2F;&#x2F; when they were freed.  Add in the bytes evacuated.
          increase_used(g1_policy()-&gt;bytes_copied_during_gc());
        &#125;

        if (collector_state()-&gt;in_initial_mark_gc()) &#123;
          &#x2F;&#x2F; We have to do this before we notify the CM threads that
          &#x2F;&#x2F; they can start working to make sure that all the
          &#x2F;&#x2F; appropriate initialization is done on the CM object.
          concurrent_mark()-&gt;post_initial_mark();
          &#x2F;&#x2F; Note that we don&#39;t actually trigger the CM thread at
          &#x2F;&#x2F; this point. We do that later when we&#39;re sure that
          &#x2F;&#x2F; the current thread has completed its logging output.
        &#125;

        allocate_dummy_regions();

        _allocator-&gt;init_mutator_alloc_region();

        &#123;
          size_t expand_bytes &#x3D; _heap_sizing_policy-&gt;expansion_amount();
          if (expand_bytes &gt; 0) &#123;
            size_t bytes_before &#x3D; capacity();
            &#x2F;&#x2F; No need for an ergo logging here,
            &#x2F;&#x2F; expansion_amount() does this when it returns a value &gt; 0.
            double expand_ms;
            if (!expand(expand_bytes, _workers, &amp;expand_ms)) &#123;
              &#x2F;&#x2F; We failed to expand the heap. Cannot do anything about it.
            &#125;
            g1_policy()-&gt;phase_times()-&gt;record_expand_heap_time(expand_ms);
          &#125;
        &#125;

        &#x2F;&#x2F; We redo the verification but now wrt to the new CSet which
        &#x2F;&#x2F; has just got initialized after the previous CSet was freed.
        _cm-&gt;verify_no_cset_oops();

        &#x2F;&#x2F; This timing is only used by the ergonomics to handle our pause target.
        &#x2F;&#x2F; It is unclear why this should not include the full pause. We will
        &#x2F;&#x2F; investigate this in CR 7178365.
        double sample_end_time_sec &#x3D; os::elapsedTime();
        double pause_time_ms &#x3D; (sample_end_time_sec - sample_start_time_sec) * MILLIUNITS;
        size_t total_cards_scanned &#x3D; g1_policy()-&gt;phase_times()-&gt;sum_thread_work_items(G1GCPhaseTimes::ScanRS, G1GCPhaseTimes::ScanRSScannedCards);
        g1_policy()-&gt;record_collection_pause_end(pause_time_ms, total_cards_scanned, heap_used_bytes_before_gc);

        evacuation_info.set_collectionset_used_before(collection_set()-&gt;bytes_used_before());
        evacuation_info.set_bytes_copied(g1_policy()-&gt;bytes_copied_during_gc());

        if (VerifyRememberedSets) &#123;
          log_info(gc, verify)(&quot;[Verifying RemSets after GC]&quot;);
          VerifyRegionRemSetClosure v_cl;
          heap_region_iterate(&amp;v_cl);
        &#125;

        _verifier-&gt;verify_after_gc(verify_type);
        _verifier-&gt;check_bitmaps(&quot;GC End&quot;);

        assert(!_ref_processor_stw-&gt;discovery_enabled(), &quot;Postcondition&quot;);
        _ref_processor_stw-&gt;verify_no_references_recorded();

        &#x2F;&#x2F; CM reference discovery will be re-enabled if necessary.
      &#125;

#ifdef TRACESPINNING
      ParallelTaskTerminator::print_termination_counts();
#endif

      gc_epilogue(false);
    &#125;

    &#x2F;&#x2F; Print the remainder of the GC log output.
    if (evacuation_failed()) &#123;
      log_info(gc)(&quot;To-space exhausted&quot;);
    &#125;

    g1_policy()-&gt;print_phases();
    heap_transition.print();

    &#x2F;&#x2F; It is not yet to safe to tell the concurrent mark to
    &#x2F;&#x2F; start as we have some optional output below. We don&#39;t want the
    &#x2F;&#x2F; output from the concurrent mark thread interfering with this
    &#x2F;&#x2F; logging output either.

    _hrm.verify_optional();
    _verifier-&gt;verify_region_sets_optional();

    TASKQUEUE_STATS_ONLY(print_taskqueue_stats());
    TASKQUEUE_STATS_ONLY(reset_taskqueue_stats());

    print_heap_after_gc();
    print_heap_regions();
    trace_heap_after_gc(_gc_tracer_stw);

    &#x2F;&#x2F; We must call G1MonitoringSupport::update_sizes() in the same scoping level
    &#x2F;&#x2F; as an active TraceMemoryManagerStats object (i.e. before the destructor for the
    &#x2F;&#x2F; TraceMemoryManagerStats is called) so that the G1 memory pools are updated
    &#x2F;&#x2F; before any GC notifications are raised.
    g1mm()-&gt;update_sizes();

    _gc_tracer_stw-&gt;report_evacuation_info(&amp;evacuation_info);
    _gc_tracer_stw-&gt;report_tenuring_threshold(_g1_policy-&gt;tenuring_threshold());
    _gc_timer_stw-&gt;register_gc_end();
    _gc_tracer_stw-&gt;report_gc_end(_gc_timer_stw-&gt;gc_end(), _gc_timer_stw-&gt;time_partitions());
  &#125;
  &#x2F;&#x2F; It should now be safe to tell the concurrent mark thread to start
  &#x2F;&#x2F; without its logging output interfering with the logging output
  &#x2F;&#x2F; that came from the pause.

  if (should_start_conc_mark) &#123;
    &#x2F;&#x2F; CAUTION: after the doConcurrentMark() call below,
    &#x2F;&#x2F; the concurrent marking thread(s) could be running
    &#x2F;&#x2F; concurrently with us. Make sure that anything after
    &#x2F;&#x2F; this point does not assume that we are the only GC thread
    &#x2F;&#x2F; running. Note: of course, the actual marking work will
    &#x2F;&#x2F; not start until the safepoint itself is released in
    &#x2F;&#x2F; SuspendibleThreadSet::desynchronize().
    do_concurrent_mark();
  &#125;

  return true;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>往下走就是这一步<code>G1Policy::finalize_collection_set</code>,去处理新生代和老年代</p>
<pre class="line-numbers language-C++" data-language="C++"><code class="language-C++">void G1Policy::finalize_collection_set(double target_pause_time_ms, G1SurvivorRegions* survivor) &#123;
  double time_remaining_ms &#x3D; _collection_set-&gt;finalize_young_part(target_pause_time_ms, survivor);
  _collection_set-&gt;finalize_old_part(time_remaining_ms);
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>这里分别调用了两个方法，可以看到剩余时间是往下传的，来看一下具体的方法</p>
<pre class="line-numbers language-C++" data-language="C++"><code class="language-C++">double G1CollectionSet::finalize_young_part(double target_pause_time_ms, G1SurvivorRegions* survivors) &#123;
  double young_start_time_sec &#x3D; os::elapsedTime();

  finalize_incremental_building();

  guarantee(target_pause_time_ms &gt; 0.0,
            &quot;target_pause_time_ms &#x3D; %1.6lf should be positive&quot;, target_pause_time_ms);

  size_t pending_cards &#x3D; _policy-&gt;pending_cards();
  double base_time_ms &#x3D; _policy-&gt;predict_base_elapsed_time_ms(pending_cards);
  double time_remaining_ms &#x3D; MAX2(target_pause_time_ms - base_time_ms, 0.0);

  log_trace(gc, ergo, cset)(&quot;Start choosing CSet. pending cards: &quot; SIZE_FORMAT &quot; predicted base time: %1.2fms remaining time: %1.2fms target pause time: %1.2fms&quot;,
                            pending_cards, base_time_ms, time_remaining_ms, target_pause_time_ms);

  &#x2F;&#x2F; The young list is laid with the survivor regions from the previous
  &#x2F;&#x2F; pause are appended to the RHS of the young list, i.e.
  &#x2F;&#x2F;   [Newly Young Regions ++ Survivors from last pause].

  uint survivor_region_length &#x3D; survivors-&gt;length();
  uint eden_region_length &#x3D; _g1h-&gt;eden_regions_count();
  init_region_lengths(eden_region_length, survivor_region_length);

  verify_young_cset_indices();

  &#x2F;&#x2F; Clear the fields that point to the survivor list - they are all young now.
  survivors-&gt;convert_to_eden();

  _bytes_used_before &#x3D; _inc_bytes_used_before;
  time_remaining_ms &#x3D; MAX2(time_remaining_ms - _inc_predicted_elapsed_time_ms, 0.0);

  log_trace(gc, ergo, cset)(&quot;Add young regions to CSet. eden: %u regions, survivors: %u regions, predicted young region time: %1.2fms, target pause time: %1.2fms&quot;,
                            eden_region_length, survivor_region_length, _inc_predicted_elapsed_time_ms, target_pause_time_ms);

  &#x2F;&#x2F; The number of recorded young regions is the incremental
  &#x2F;&#x2F; collection set&#39;s current size
  set_recorded_rs_lengths(_inc_recorded_rs_lengths);

  double young_end_time_sec &#x3D; os::elapsedTime();
  phase_times()-&gt;record_young_cset_choice_time_ms((young_end_time_sec - young_start_time_sec) * 1000.0);

  return time_remaining_ms;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>下面是老年代的部分</p>
<pre class="line-numbers language-C++" data-language="C++"><code class="language-C++">void G1CollectionSet::finalize_old_part(double time_remaining_ms) &#123;
  double non_young_start_time_sec &#x3D; os::elapsedTime();
  double predicted_old_time_ms &#x3D; 0.0;

  if (collector_state()-&gt;in_mixed_phase()) &#123;
    cset_chooser()-&gt;verify();
    const uint min_old_cset_length &#x3D; _policy-&gt;calc_min_old_cset_length();
    const uint max_old_cset_length &#x3D; _policy-&gt;calc_max_old_cset_length();

    uint expensive_region_num &#x3D; 0;
    bool check_time_remaining &#x3D; _policy-&gt;adaptive_young_list_length();

    HeapRegion* hr &#x3D; cset_chooser()-&gt;peek();
    while (hr !&#x3D; NULL) &#123;
      if (old_region_length() &gt;&#x3D; max_old_cset_length) &#123;
        &#x2F;&#x2F; Added maximum number of old regions to the CSet.
        log_debug(gc, ergo, cset)(&quot;Finish adding old regions to CSet (old CSet region num reached max). old %u regions, max %u regions&quot;,
                                  old_region_length(), max_old_cset_length);
        break;
      &#125;

      &#x2F;&#x2F; Stop adding regions if the remaining reclaimable space is
      &#x2F;&#x2F; not above G1HeapWastePercent.
      size_t reclaimable_bytes &#x3D; cset_chooser()-&gt;remaining_reclaimable_bytes();
      double reclaimable_percent &#x3D; _policy-&gt;reclaimable_bytes_percent(reclaimable_bytes);
      double threshold &#x3D; (double) G1HeapWastePercent;
      if (reclaimable_percent &lt;&#x3D; threshold) &#123;
        &#x2F;&#x2F; We&#39;ve added enough old regions that the amount of uncollected
        &#x2F;&#x2F; reclaimable space is at or below the waste threshold. Stop
        &#x2F;&#x2F; adding old regions to the CSet.
        log_debug(gc, ergo, cset)(&quot;Finish adding old regions to CSet (reclaimable percentage not over threshold). &quot;
                                  &quot;old %u regions, max %u regions, reclaimable: &quot; SIZE_FORMAT &quot;B (%1.2f%%) threshold: &quot; UINTX_FORMAT &quot;%%&quot;,
                                  old_region_length(), max_old_cset_length, reclaimable_bytes, reclaimable_percent, G1HeapWastePercent);
        break;
      &#125;

      double predicted_time_ms &#x3D; predict_region_elapsed_time_ms(hr);
      if (check_time_remaining) &#123;
        if (predicted_time_ms &gt; time_remaining_ms) &#123;
          &#x2F;&#x2F; Too expensive for the current CSet.

          if (old_region_length() &gt;&#x3D; min_old_cset_length) &#123;
            &#x2F;&#x2F; We have added the minimum number of old regions to the CSet,
            &#x2F;&#x2F; we are done with this CSet.
            log_debug(gc, ergo, cset)(&quot;Finish adding old regions to CSet (predicted time is too high). &quot;
                                      &quot;predicted time: %1.2fms, remaining time: %1.2fms old %u regions, min %u regions&quot;,
                                      predicted_time_ms, time_remaining_ms, old_region_length(), min_old_cset_length);
            break;
          &#125;

          &#x2F;&#x2F; We&#39;ll add it anyway given that we haven&#39;t reached the
          &#x2F;&#x2F; minimum number of old regions.
          expensive_region_num +&#x3D; 1;
        &#125;
      &#125; else &#123;
        if (old_region_length() &gt;&#x3D; min_old_cset_length) &#123;
          &#x2F;&#x2F; In the non-auto-tuning case, we&#39;ll finish adding regions
          &#x2F;&#x2F; to the CSet if we reach the minimum.

          log_debug(gc, ergo, cset)(&quot;Finish adding old regions to CSet (old CSet region num reached min). old %u regions, min %u regions&quot;,
                                    old_region_length(), min_old_cset_length);
          break;
        &#125;
      &#125;

      &#x2F;&#x2F; We will add this region to the CSet.
      time_remaining_ms &#x3D; MAX2(time_remaining_ms - predicted_time_ms, 0.0);
      predicted_old_time_ms +&#x3D; predicted_time_ms;
      cset_chooser()-&gt;pop(); &#x2F;&#x2F; already have region via peek()
      _g1h-&gt;old_set_remove(hr);
      add_old_region(hr);

      hr &#x3D; cset_chooser()-&gt;peek();
    &#125;
    if (hr &#x3D;&#x3D; NULL) &#123;
      log_debug(gc, ergo, cset)(&quot;Finish adding old regions to CSet (candidate old regions not available)&quot;);
    &#125;

    if (expensive_region_num &gt; 0) &#123;
      &#x2F;&#x2F; We print the information once here at the end, predicated on
      &#x2F;&#x2F; whether we added any apparently expensive regions or not, to
      &#x2F;&#x2F; avoid generating output per region.
      log_debug(gc, ergo, cset)(&quot;Added expensive regions to CSet (old CSet region num not reached min).&quot;
                                &quot;old: %u regions, expensive: %u regions, min: %u regions, remaining time: %1.2fms&quot;,
                                old_region_length(), expensive_region_num, min_old_cset_length, time_remaining_ms);
    &#125;

    cset_chooser()-&gt;verify();
  &#125;

  stop_incremental_building();

  log_debug(gc, ergo, cset)(&quot;Finish choosing CSet. old: %u regions, predicted old region time: %1.2fms, time remaining: %1.2f&quot;,
                            old_region_length(), predicted_old_time_ms, time_remaining_ms);

  double non_young_end_time_sec &#x3D; os::elapsedTime();
  phase_times()-&gt;record_non_young_cset_choice_time_ms((non_young_end_time_sec - non_young_start_time_sec) * 1000.0);

  QuickSort::sort(_collection_set_regions, _collection_set_cur_length, compare_region_idx, true);
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>上面第三行是个判断，当前是否是 mixed 回收阶段，如果不是的话其实是没有老年代什么事的，所以可以看到代码基本是从这个 if 判断<br><code>if (collector_state()-&gt;in_mixed_phase()) &#123;</code>开始往下走的<br>先写到这，偏向于做笔记用，有错轻拍</p>
]]></content>
      <categories>
        <category>Java</category>
        <category>JVM</category>
        <category>GC</category>
        <category>C++</category>
      </categories>
      <tags>
        <tag>Java</tag>
        <tag>JVM</tag>
        <tag>C++</tag>
      </tags>
  </entry>
  <entry>
    <title>redis系列介绍七-过期策略</title>
    <url>/2020/04/12/redis%E7%B3%BB%E5%88%97%E4%BB%8B%E7%BB%8D%E4%B8%83/</url>
    <content><![CDATA[<p>这一篇不再是数据结构介绍了，大致的数据结构基本都介绍了，这一篇主要是查漏补缺，或者说讲一些重要且基本的概念，也可能是经常被忽略的，很多讲 redis 的系列文章可能都会忽略，学习 redis 的时候也会，因为觉得源码学习就是讲主要的数据结构和“算法”学习了就好了。<br>redis 的主要应用就是拿来作为高性能的缓存，那么缓存一般有些啥需要注意的，首先是访问速度，如果取得跟数据库一样快，那就没什么存在的意义，第二个是缓存的字面意思，我只是为了让数据读取快一些，通常大部分的场景这个是需要更新过期的，这里就把我要讲的第一点引出来了（真累，</p>
<h2 id="redis过期策略"><a href="#redis过期策略" class="headerlink" title="redis过期策略"></a>redis过期策略</h2><p>redis 是如何过期缓存的，可以猜测下，最无脑的就是每个设置了过期时间的 key 都设个定时器，过期了就删除，这种显然消耗太大，清理地最及时，还有的就是 redis 正在采用的懒汉清理策略和定期清理<br>懒汉策略就是在使用的时候去检查缓存是否过期，比如 get 操作时，先判断下这个 key 是否已经过期了，如果过期了就删掉，并且返回空，如果没过期则正常返回<br>主要代码是</p>
<pre class="line-numbers language-C" data-language="C"><code class="language-C">&#x2F;* This function is called when we are going to perform some operation
 * in a given key, but such key may be already logically expired even if
 * it still exists in the database. The main way this function is called
 * is via lookupKey*() family of functions.
 *
 * The behavior of the function depends on the replication role of the
 * instance, because slave instances do not expire keys, they wait
 * for DELs from the master for consistency matters. However even
 * slaves will try to have a coherent return value for the function,
 * so that read commands executed in the slave side will be able to
 * behave like if the key is expired even if still present (because the
 * master has yet to propagate the DEL).
 *
 * In masters as a side effect of finding a key which is expired, such
 * key will be evicted from the database. Also this may trigger the
 * propagation of a DEL&#x2F;UNLINK command in AOF &#x2F; replication stream.
 *
 * The return value of the function is 0 if the key is still valid,
 * otherwise the function returns 1 if the key is expired. *&#x2F;
int expireIfNeeded(redisDb *db, robj *key) &#123;
    if (!keyIsExpired(db,key)) return 0;

    &#x2F;* If we are running in the context of a slave, instead of
     * evicting the expired key from the database, we return ASAP:
     * the slave key expiration is controlled by the master that will
     * send us synthesized DEL operations for expired keys.
     *
     * Still we try to return the right information to the caller,
     * that is, 0 if we think the key should be still valid, 1 if
     * we think the key is expired at this time. *&#x2F;
    if (server.masterhost !&#x3D; NULL) return 1;

    &#x2F;* Delete the key *&#x2F;
    server.stat_expiredkeys++;
    propagateExpire(db,key,server.lazyfree_lazy_expire);
    notifyKeyspaceEvent(NOTIFY_EXPIRED,
        &quot;expired&quot;,key,db-&gt;id);
    return server.lazyfree_lazy_expire ? dbAsyncDelete(db,key) :
                                         dbSyncDelete(db,key);
&#125;

&#x2F;* Check if the key is expired. *&#x2F;
int keyIsExpired(redisDb *db, robj *key) &#123;
    mstime_t when &#x3D; getExpire(db,key);
    mstime_t now;

    if (when &lt; 0) return 0; &#x2F;* No expire for this key *&#x2F;

    &#x2F;* Don&#39;t expire anything while loading. It will be done later. *&#x2F;
    if (server.loading) return 0;

    &#x2F;* If we are in the context of a Lua script, we pretend that time is
     * blocked to when the Lua script started. This way a key can expire
     * only the first time it is accessed and not in the middle of the
     * script execution, making propagation to slaves &#x2F; AOF consistent.
     * See issue #1525 on Github for more information. *&#x2F;
    if (server.lua_caller) &#123;
        now &#x3D; server.lua_time_start;
    &#125;
    &#x2F;* If we are in the middle of a command execution, we still want to use
     * a reference time that does not change: in that case we just use the
     * cached time, that we update before each call in the call() function.
     * This way we avoid that commands such as RPOPLPUSH or similar, that
     * may re-open the same key multiple times, can invalidate an already
     * open object in a next call, if the next call will see the key expired,
     * while the first did not. *&#x2F;
    else if (server.fixed_time_expire &gt; 0) &#123;
        now &#x3D; server.mstime;
    &#125;
    &#x2F;* For the other cases, we want to use the most fresh time we have. *&#x2F;
    else &#123;
        now &#x3D; mstime();
    &#125;

    &#x2F;* The key expired if the current (virtual or real) time is greater
     * than the expire time of the key. *&#x2F;
    return now &gt; when;
&#125;
&#x2F;* Return the expire time of the specified key, or -1 if no expire
 * is associated with this key (i.e. the key is non volatile) *&#x2F;
long long getExpire(redisDb *db, robj *key) &#123;
    dictEntry *de;

    &#x2F;* No expire? return ASAP *&#x2F;
    if (dictSize(db-&gt;expires) &#x3D;&#x3D; 0 ||
       (de &#x3D; dictFind(db-&gt;expires,key-&gt;ptr)) &#x3D;&#x3D; NULL) return -1;

    &#x2F;* The entry was found in the expire dict, this means it should also
     * be present in the main dict (safety check). *&#x2F;
    serverAssertWithInfo(NULL,key,dictFind(db-&gt;dict,key-&gt;ptr) !&#x3D; NULL);
    return dictGetSignedIntegerVal(de);
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这里有几点要注意的，第一是当惰性删除时会根据lazyfree_lazy_expire这个参数去判断是执行同步删除还是异步删除，另外一点是对于 slave，是不需要执行的，因为会在 master 过期时向 slave 发送 del 指令。<br>光采用这个策略会有什么问题呢，假如一些key 一直未被访问，那这些 key 就不会过期了，导致一直被占用着内存，所以 redis 采取了懒汉式过期加定期过期策略，定期策略是怎么执行的呢</p>
<pre class="line-numbers language-C" data-language="C"><code class="language-C">&#x2F;* This function handles &#39;background&#39; operations we are required to do
 * incrementally in Redis databases, such as active key expiring, resizing,
 * rehashing. *&#x2F;
void databasesCron(void) &#123;
    &#x2F;* Expire keys by random sampling. Not required for slaves
     * as master will synthesize DELs for us. *&#x2F;
    if (server.active_expire_enabled) &#123;
        if (server.masterhost &#x3D;&#x3D; NULL) &#123;
            activeExpireCycle(ACTIVE_EXPIRE_CYCLE_SLOW);
        &#125; else &#123;
            expireSlaveKeys();
        &#125;
    &#125;

    &#x2F;* Defrag keys gradually. *&#x2F;
    activeDefragCycle();

    &#x2F;* Perform hash tables rehashing if needed, but only if there are no
     * other processes saving the DB on disk. Otherwise rehashing is bad
     * as will cause a lot of copy-on-write of memory pages. *&#x2F;
    if (!hasActiveChildProcess()) &#123;
        &#x2F;* We use global counters so if we stop the computation at a given
         * DB we&#39;ll be able to start from the successive in the next
         * cron loop iteration. *&#x2F;
        static unsigned int resize_db &#x3D; 0;
        static unsigned int rehash_db &#x3D; 0;
        int dbs_per_call &#x3D; CRON_DBS_PER_CALL;
        int j;

        &#x2F;* Don&#39;t test more DBs than we have. *&#x2F;
        if (dbs_per_call &gt; server.dbnum) dbs_per_call &#x3D; server.dbnum;

        &#x2F;* Resize *&#x2F;
        for (j &#x3D; 0; j &lt; dbs_per_call; j++) &#123;
            tryResizeHashTables(resize_db % server.dbnum);
            resize_db++;
        &#125;

        &#x2F;* Rehash *&#x2F;
        if (server.activerehashing) &#123;
            for (j &#x3D; 0; j &lt; dbs_per_call; j++) &#123;
                int work_done &#x3D; incrementallyRehash(rehash_db);
                if (work_done) &#123;
                    &#x2F;* If the function did some work, stop here, we&#39;ll do
                     * more at the next cron loop. *&#x2F;
                    break;
                &#125; else &#123;
                    &#x2F;* If this db didn&#39;t need rehash, we&#39;ll try the next one. *&#x2F;
                    rehash_db++;
                    rehash_db %&#x3D; server.dbnum;
                &#125;
            &#125;
        &#125;
    &#125;
&#125;
&#x2F;* Try to expire a few timed out keys. The algorithm used is adaptive and
 * will use few CPU cycles if there are few expiring keys, otherwise
 * it will get more aggressive to avoid that too much memory is used by
 * keys that can be removed from the keyspace.
 *
 * Every expire cycle tests multiple databases: the next call will start
 * again from the next db, with the exception of exists for time limit: in that
 * case we restart again from the last database we were processing. Anyway
 * no more than CRON_DBS_PER_CALL databases are tested at every iteration.
 *
 * The function can perform more or less work, depending on the &quot;type&quot;
 * argument. It can execute a &quot;fast cycle&quot; or a &quot;slow cycle&quot;. The slow
 * cycle is the main way we collect expired cycles: this happens with
 * the &quot;server.hz&quot; frequency (usually 10 hertz).
 *
 * However the slow cycle can exit for timeout, since it used too much time.
 * For this reason the function is also invoked to perform a fast cycle
 * at every event loop cycle, in the beforeSleep() function. The fast cycle
 * will try to perform less work, but will do it much more often.
 *
 * The following are the details of the two expire cycles and their stop
 * conditions:
 *
 * If type is ACTIVE_EXPIRE_CYCLE_FAST the function will try to run a
 * &quot;fast&quot; expire cycle that takes no longer than EXPIRE_FAST_CYCLE_DURATION
 * microseconds, and is not repeated again before the same amount of time.
 * The cycle will also refuse to run at all if the latest slow cycle did not
 * terminate because of a time limit condition.
 *
 * If type is ACTIVE_EXPIRE_CYCLE_SLOW, that normal expire cycle is
 * executed, where the time limit is a percentage of the REDIS_HZ period
 * as specified by the ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC define. In the
 * fast cycle, the check of every database is interrupted once the number
 * of already expired keys in the database is estimated to be lower than
 * a given percentage, in order to avoid doing too much work to gain too
 * little memory.
 *
 * The configured expire &quot;effort&quot; will modify the baseline parameters in
 * order to do more work in both the fast and slow expire cycles.
 *&#x2F;

#define ACTIVE_EXPIRE_CYCLE_KEYS_PER_LOOP 20 &#x2F;* Keys for each DB loop. *&#x2F;
#define ACTIVE_EXPIRE_CYCLE_FAST_DURATION 1000 &#x2F;* Microseconds. *&#x2F;
#define ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC 25 &#x2F;* Max % of CPU to use. *&#x2F;
#define ACTIVE_EXPIRE_CYCLE_ACCEPTABLE_STALE 10 &#x2F;* % of stale keys after which
                                                   we do extra efforts. *&#x2F;
void activeExpireCycle(int type) &#123;
    &#x2F;* Adjust the running parameters according to the configured expire
     * effort. The default effort is 1, and the maximum configurable effort
     * is 10. *&#x2F;
    unsigned long
    effort &#x3D; server.active_expire_effort-1, &#x2F;* Rescale from 0 to 9. *&#x2F;
    config_keys_per_loop &#x3D; ACTIVE_EXPIRE_CYCLE_KEYS_PER_LOOP +
                           ACTIVE_EXPIRE_CYCLE_KEYS_PER_LOOP&#x2F;4*effort,
    config_cycle_fast_duration &#x3D; ACTIVE_EXPIRE_CYCLE_FAST_DURATION +
                                 ACTIVE_EXPIRE_CYCLE_FAST_DURATION&#x2F;4*effort,
    config_cycle_slow_time_perc &#x3D; ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC +
                                  2*effort,
    config_cycle_acceptable_stale &#x3D; ACTIVE_EXPIRE_CYCLE_ACCEPTABLE_STALE-
                                    effort;

    &#x2F;* This function has some global state in order to continue the work
     * incrementally across calls. *&#x2F;
    static unsigned int current_db &#x3D; 0; &#x2F;* Last DB tested. *&#x2F;
    static int timelimit_exit &#x3D; 0;      &#x2F;* Time limit hit in previous call? *&#x2F;
    static long long last_fast_cycle &#x3D; 0; &#x2F;* When last fast cycle ran. *&#x2F;

    int j, iteration &#x3D; 0;
    int dbs_per_call &#x3D; CRON_DBS_PER_CALL;
    long long start &#x3D; ustime(), timelimit, elapsed;

    &#x2F;* When clients are paused the dataset should be static not just from the
     * POV of clients not being able to write, but also from the POV of
     * expires and evictions of keys not being performed. *&#x2F;
    if (clientsArePaused()) return;

    if (type &#x3D;&#x3D; ACTIVE_EXPIRE_CYCLE_FAST) &#123;
        &#x2F;* Don&#39;t start a fast cycle if the previous cycle did not exit
         * for time limit, unless the percentage of estimated stale keys is
         * too high. Also never repeat a fast cycle for the same period
         * as the fast cycle total duration itself. *&#x2F;
        if (!timelimit_exit &amp;&amp;
            server.stat_expired_stale_perc &lt; config_cycle_acceptable_stale)
            return;

        if (start &lt; last_fast_cycle + (long long)config_cycle_fast_duration*2)
            return;

        last_fast_cycle &#x3D; start;
    &#125;

    &#x2F;* We usually should test CRON_DBS_PER_CALL per iteration, with
     * two exceptions:
     *
     * 1) Don&#39;t test more DBs than we have.
     * 2) If last time we hit the time limit, we want to scan all DBs
     * in this iteration, as there is work to do in some DB and we don&#39;t want
     * expired keys to use memory for too much time. *&#x2F;
    if (dbs_per_call &gt; server.dbnum || timelimit_exit)
        dbs_per_call &#x3D; server.dbnum;

    &#x2F;* We can use at max &#39;config_cycle_slow_time_perc&#39; percentage of CPU
     * time per iteration. Since this function gets called with a frequency of
     * server.hz times per second, the following is the max amount of
     * microseconds we can spend in this function. *&#x2F;
    timelimit &#x3D; config_cycle_slow_time_perc*1000000&#x2F;server.hz&#x2F;100;
    timelimit_exit &#x3D; 0;
    if (timelimit &lt;&#x3D; 0) timelimit &#x3D; 1;

    if (type &#x3D;&#x3D; ACTIVE_EXPIRE_CYCLE_FAST)
        timelimit &#x3D; config_cycle_fast_duration; &#x2F;* in microseconds. *&#x2F;

    &#x2F;* Accumulate some global stats as we expire keys, to have some idea
     * about the number of keys that are already logically expired, but still
     * existing inside the database. *&#x2F;
    long total_sampled &#x3D; 0;
    long total_expired &#x3D; 0;

    for (j &#x3D; 0; j &lt; dbs_per_call &amp;&amp; timelimit_exit &#x3D;&#x3D; 0; j++) &#123;
        &#x2F;* Expired and checked in a single loop. *&#x2F;
        unsigned long expired, sampled;

        redisDb *db &#x3D; server.db+(current_db % server.dbnum);

        &#x2F;* Increment the DB now so we are sure if we run out of time
         * in the current DB we&#39;ll restart from the next. This allows to
         * distribute the time evenly across DBs. *&#x2F;
        current_db++;

        &#x2F;* Continue to expire if at the end of the cycle more than 25%
         * of the keys were expired. *&#x2F;
        do &#123;
            unsigned long num, slots;
            long long now, ttl_sum;
            int ttl_samples;
            iteration++;

            &#x2F;* If there is nothing to expire try next DB ASAP. *&#x2F;
            if ((num &#x3D; dictSize(db-&gt;expires)) &#x3D;&#x3D; 0) &#123;
                db-&gt;avg_ttl &#x3D; 0;
                break;
            &#125;
            slots &#x3D; dictSlots(db-&gt;expires);
            now &#x3D; mstime();

            &#x2F;* When there are less than 1% filled slots, sampling the key
             * space is expensive, so stop here waiting for better times...
             * The dictionary will be resized asap. *&#x2F;
            if (num &amp;&amp; slots &gt; DICT_HT_INITIAL_SIZE &amp;&amp;
                (num*100&#x2F;slots &lt; 1)) break;

            &#x2F;* The main collection cycle. Sample random keys among keys
             * with an expire set, checking for expired ones. *&#x2F;
            expired &#x3D; 0;
            sampled &#x3D; 0;
            ttl_sum &#x3D; 0;
            ttl_samples &#x3D; 0;

            if (num &gt; config_keys_per_loop)
                num &#x3D; config_keys_per_loop;

            &#x2F;* Here we access the low level representation of the hash table
             * for speed concerns: this makes this code coupled with dict.c,
             * but it hardly changed in ten years.
             *
             * Note that certain places of the hash table may be empty,
             * so we want also a stop condition about the number of
             * buckets that we scanned. However scanning for free buckets
             * is very fast: we are in the cache line scanning a sequential
             * array of NULL pointers, so we can scan a lot more buckets
             * than keys in the same time. *&#x2F;
            long max_buckets &#x3D; num*20;
            long checked_buckets &#x3D; 0;

            while (sampled &lt; num &amp;&amp; checked_buckets &lt; max_buckets) &#123;
                for (int table &#x3D; 0; table &lt; 2; table++) &#123;
                    if (table &#x3D;&#x3D; 1 &amp;&amp; !dictIsRehashing(db-&gt;expires)) break;

                    unsigned long idx &#x3D; db-&gt;expires_cursor;
                    idx &amp;&#x3D; db-&gt;expires-&gt;ht[table].sizemask;
                    dictEntry *de &#x3D; db-&gt;expires-&gt;ht[table].table[idx];
                    long long ttl;

                    &#x2F;* Scan the current bucket of the current table. *&#x2F;
                    checked_buckets++;
                    while(de) &#123;
                        &#x2F;* Get the next entry now since this entry may get
                         * deleted. *&#x2F;
                        dictEntry *e &#x3D; de;
                        de &#x3D; de-&gt;next;

                        ttl &#x3D; dictGetSignedIntegerVal(e)-now;
                        if (activeExpireCycleTryExpire(db,e,now)) expired++;
                        if (ttl &gt; 0) &#123;
                            &#x2F;* We want the average TTL of keys yet
                             * not expired. *&#x2F;
                            ttl_sum +&#x3D; ttl;
                            ttl_samples++;
                        &#125;
                        sampled++;
                    &#125;
                &#125;
                db-&gt;expires_cursor++;
            &#125;
            total_expired +&#x3D; expired;
            total_sampled +&#x3D; sampled;

            &#x2F;* Update the average TTL stats for this database. *&#x2F;
            if (ttl_samples) &#123;
                long long avg_ttl &#x3D; ttl_sum&#x2F;ttl_samples;

                &#x2F;* Do a simple running average with a few samples.
                 * We just use the current estimate with a weight of 2%
                 * and the previous estimate with a weight of 98%. *&#x2F;
                if (db-&gt;avg_ttl &#x3D;&#x3D; 0) db-&gt;avg_ttl &#x3D; avg_ttl;
                db-&gt;avg_ttl &#x3D; (db-&gt;avg_ttl&#x2F;50)*49 + (avg_ttl&#x2F;50);
            &#125;

            &#x2F;* We can&#39;t block forever here even if there are many keys to
             * expire. So after a given amount of milliseconds return to the
             * caller waiting for the other active expire cycle. *&#x2F;
            if ((iteration &amp; 0xf) &#x3D;&#x3D; 0) &#123; &#x2F;* check once every 16 iterations. *&#x2F;
                elapsed &#x3D; ustime()-start;
                if (elapsed &gt; timelimit) &#123;
                    timelimit_exit &#x3D; 1;
                    server.stat_expired_time_cap_reached_count++;
                    break;
                &#125;
            &#125;
            &#x2F;* We don&#39;t repeat the cycle for the current database if there are
             * an acceptable amount of stale keys (logically expired but yet
             * not reclained). *&#x2F;
        &#125; while ((expired*100&#x2F;sampled) &gt; config_cycle_acceptable_stale);
    &#125;

    elapsed &#x3D; ustime()-start;
    server.stat_expire_cycle_time_used +&#x3D; elapsed;
    latencyAddSampleIfNeeded(&quot;expire-cycle&quot;,elapsed&#x2F;1000);

    &#x2F;* Update our estimate of keys existing but yet to be expired.
     * Running average with this sample accounting for 5%. *&#x2F;
    double current_perc;
    if (total_sampled) &#123;
        current_perc &#x3D; (double)total_expired&#x2F;total_sampled;
    &#125; else
        current_perc &#x3D; 0;
    server.stat_expired_stale_perc &#x3D; (current_perc*0.05)+
                                     (server.stat_expired_stale_perc*0.95);
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>执行定期清除分成两种类型，快和慢，分别由<code>beforeSleep</code>和<code>databasesCron</code>调用，快版有两个限制，一个是执行时长由ACTIVE_EXPIRE_CYCLE_FAST_DURATION限制，另一个是执行间隔是 2 倍的ACTIVE_EXPIRE_CYCLE_FAST_DURATION，另外这还可以由配置的server.active_expire_effort参数来控制，默认是 1，最大是 10</p>
<pre class="line-numbers language-C" data-language="C"><code class="language-C">onfig_cycle_fast_duration &#x3D; ACTIVE_EXPIRE_CYCLE_FAST_DURATION +
                                 ACTIVE_EXPIRE_CYCLE_FAST_DURATION&#x2F;4*effort<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>然后会从一定数量的 db 中找出一定数量的带过期时间的 key（保存在 expires中），这里的数量是由</p>
<pre class="line-numbers language-C" data-language="C"><code class="language-C">config_keys_per_loop &#x3D; ACTIVE_EXPIRE_CYCLE_KEYS_PER_LOOP +
                           ACTIVE_EXPIRE_CYCLE_KEYS_PER_LOOP&#x2F;4*effort
&#96;&#96;&#96;                                 
控制，慢速的执行时长是
&#96;&#96;&#96;C
config_cycle_slow_time_perc &#x3D; ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC +
                                  2*effort
timelimit &#x3D; config_cycle_slow_time_perc*1000000&#x2F;server.hz&#x2F;100;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这里还有一个额外的退出条件，如果当前数据库的抽样结果已经达到我们所允许的过期 key 百分比，则下次不再处理当前 db，继续处理下个 db</p>
]]></content>
      <categories>
        <category>Redis</category>
        <category>数据结构</category>
        <category>C</category>
        <category>源码</category>
        <category>Redis</category>
      </categories>
      <tags>
        <tag>redis</tag>
        <tag>数据结构</tag>
        <tag>源码</tag>
      </tags>
  </entry>
  <entry>
    <title>redis系列介绍八-淘汰策略</title>
    <url>/2020/04/18/redis%E7%B3%BB%E5%88%97%E4%BB%8B%E7%BB%8D%E5%85%AB/</url>
    <content><![CDATA[<h3 id="LRU"><a href="#LRU" class="headerlink" title="LRU"></a>LRU</h3><p>说完了过期策略再说下淘汰策略，redis 使用的策略是近似的 lru 策略，为什么是近似的呢，先来看下什么是 lru，看下 wiki 的介绍<br><img data-src="https://i.loli.net/2020/04/14/wWyhc2dQfb4BYsK.png">，图中一共有四个槽的存储空间，依次访问顺序是 A B C D E D F，<br>当第一次访问 D 时刚好占满了坑，并且值是 4，这个值越小代表越先被淘汰，当 E 进来时，看了下已经存在的四个里 A 是最小的，代表是最早存在并且最早被访问的，那就先淘汰它了，E 占领了 A 的位置，并设置值为 4，然后又访问 D 了，D 已经存在了，不过又被访问到了，得更新值为 5，然后是 F 进来了，这时 B 是最老的且最近未被访问，所以就淘汰它了。以上是一个 lru 的简要说明，但是 redis 没有严格按照这个去执行，理由跟前面过期策略一致，最严格的过期策略应该是每个 key 都有对应的定时器，当超时时马上就能清除，但是问题是这样的cpu 消耗太大，所换来的内存效率不太值得，淘汰策略也是这样，类似于上图，要维护所有 key 的一个有序 lru 值，并且遍历将最小的淘汰，redis 采用的是抽样的形式，最初的实现方式是随机从 dict 抽取 5 个 key，淘汰一个 lru 最小的，这样子勉强能达到淘汰的目的，但是效果不是特别好，后面在 redis 3.0开始，将随机抽取改成了维护一个 pool，pool 的大小默认是 16，每次放入的都是按lru 值有序排列好，每一次放入的必须是 lru小于 pool 中最小的 lru 才允许放入，直到放满，后面再有新的就会将大的踢出。<br>redis 针对这个策略的改进做了一个实验，这里借用下图<br><img data-src="https://i.loli.net/2020/04/18/QwcROpB345ezEkX.png"><br>首先背景是这图中的所有点都对应一个 redis 的 key，灰色部分加入后被顺序访问过一遍，然后又加入了绿色部分，那么按照理论的 lru 算法，应该是图左上中，浅灰色部分全都被淘汰，那么对比来看看图右上，左下和右下，左下表示 2.8 版本就是随机抽样 5 个 key，淘汰其中 lru 最小的一个，发现是灰色和浅灰色的都有被淘汰的，右下的 3.0 版本抽样数量不变的情况下，稍好一些，当 3.0 版本的抽样数量调整成 10 后，已经较为接近理论上的 lru 策略了，通过代码来简要分析下</p>
<pre class="line-numbers language-C" data-language="C"><code class="language-C">typedef struct redisObject &#123;
    unsigned type:4;
    unsigned encoding:4;
    unsigned lru:LRU_BITS; &#x2F;* LRU time (relative to global lru_clock) or
                            * LFU data (least significant 8 bits frequency
                            * and most significant 16 bits access time). *&#x2F;
    int refcount;
    void *ptr;
&#125; robj;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>对于 lru 策略来说，lru 字段记录的就是<a href="https://github.com/antirez/redis/blob/unstable/src/server.h#L603"><code>redisObj</code></a> 的LRU time，<br>redis 在访问数据时，都会调用<a href="https://github.com/antirez/redis/blob/unstable/src/db.c#L55"><code>lookupKey</code></a>方法</p>
<pre class="line-numbers language-C" data-language="C"><code class="language-C">&#x2F;* Low level key lookup API, not actually called directly from commands
 * implementations that should instead rely on lookupKeyRead(),
 * lookupKeyWrite() and lookupKeyReadWithFlags(). *&#x2F;
robj *lookupKey(redisDb *db, robj *key, int flags) &#123;
    dictEntry *de &#x3D; dictFind(db-&gt;dict,key-&gt;ptr);
    if (de) &#123;
        robj *val &#x3D; dictGetVal(de);

        &#x2F;* Update the access time for the ageing algorithm.
         * Don&#39;t do it if we have a saving child, as this will trigger
         * a copy on write madness. *&#x2F;
        if (!hasActiveChildProcess() &amp;&amp; !(flags &amp; LOOKUP_NOTOUCH))&#123;
            if (server.maxmemory_policy &amp; MAXMEMORY_FLAG_LFU) &#123;
                &#x2F;&#x2F; 这个是后面一节的内容
                updateLFU(val);
            &#125; else &#123;
                &#x2F;&#x2F;  对于这个分支，访问时就会去更新 lru 值
                val-&gt;lru &#x3D; LRU_CLOCK();
            &#125;
        &#125;
        return val;
    &#125; else &#123;
        return NULL;
    &#125;
&#125;
&#x2F;* This function is used to obtain the current LRU clock.
 * If the current resolution is lower than the frequency we refresh the
 * LRU clock (as it should be in production servers) we return the
 * precomputed value, otherwise we need to resort to a system call. *&#x2F;
unsigned int LRU_CLOCK(void) &#123;
    unsigned int lruclock;
    if (1000&#x2F;server.hz &lt;&#x3D; LRU_CLOCK_RESOLUTION) &#123;
        &#x2F;&#x2F; 如果服务器的频率server.hz大于 1 时就是用系统预设的 lruclock
        lruclock &#x3D; server.lruclock;
    &#125; else &#123;
        lruclock &#x3D; getLRUClock();
    &#125;
    return lruclock;
&#125;
&#x2F;* Return the LRU clock, based on the clock resolution. This is a time
 * in a reduced-bits format that can be used to set and check the
 * object-&gt;lru field of redisObject structures. *&#x2F;
unsigned int getLRUClock(void) &#123;
    return (mstime()&#x2F;LRU_CLOCK_RESOLUTION) &amp; LRU_CLOCK_MAX;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>redis 处理命令是在这里<a href="https://github.com/antirez/redis/blob/unstable/src/server.c#L3355"><code>processCommand</code></a></p>
<pre class="line-numbers language-C" data-language="C"><code class="language-C">&#x2F;* If this function gets called we already read a whole
 * command, arguments are in the client argv&#x2F;argc fields.
 * processCommand() execute the command or prepare the
 * server for a bulk read from the client.
 *
 * If C_OK is returned the client is still alive and valid and
 * other operations can be performed by the caller. Otherwise
 * if C_ERR is returned the client was destroyed (i.e. after QUIT). *&#x2F;
int processCommand(client *c) &#123;
    moduleCallCommandFilters(c);

    

    &#x2F;* Handle the maxmemory directive.
     *
     * Note that we do not want to reclaim memory if we are here re-entering
     * the event loop since there is a busy Lua script running in timeout
     * condition, to avoid mixing the propagation of scripts with the
     * propagation of DELs due to eviction. *&#x2F;
    if (server.maxmemory &amp;&amp; !server.lua_timedout) &#123;
        int out_of_memory &#x3D; freeMemoryIfNeededAndSafe() &#x3D;&#x3D; C_ERR;
        &#x2F;* freeMemoryIfNeeded may flush slave output buffers. This may result
         * into a slave, that may be the active client, to be freed. *&#x2F;
        if (server.current_client &#x3D;&#x3D; NULL) return C_ERR;

        &#x2F;* It was impossible to free enough memory, and the command the client
         * is trying to execute is denied during OOM conditions or the client
         * is in MULTI&#x2F;EXEC context? Error. *&#x2F;
        if (out_of_memory &amp;&amp;
            (c-&gt;cmd-&gt;flags &amp; CMD_DENYOOM ||
             (c-&gt;flags &amp; CLIENT_MULTI &amp;&amp;
              c-&gt;cmd-&gt;proc !&#x3D; execCommand &amp;&amp;
              c-&gt;cmd-&gt;proc !&#x3D; discardCommand)))
        &#123;
            flagTransaction(c);
            addReply(c, shared.oomerr);
            return C_OK;
        &#125;
    &#125;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这里只摘了部分，当需要清理内存时就会调用, 然后调用了<a href="https://github.com/antirez/redis/blob/unstable/src/evict.c#L631"><code>freeMemoryIfNeededAndSafe</code></a></p>
<pre class="line-numbers language-C" data-language="C"><code class="language-C">&#x2F;* This is a wrapper for freeMemoryIfNeeded() that only really calls the
 * function if right now there are the conditions to do so safely:
 *
 * - There must be no script in timeout condition.
 * - Nor we are loading data right now.
 *
 *&#x2F;
int freeMemoryIfNeededAndSafe(void) &#123;
    if (server.lua_timedout || server.loading) return C_OK;
    return freeMemoryIfNeeded();
&#125;
&#x2F;* This function is periodically called to see if there is memory to free
 * according to the current &quot;maxmemory&quot; settings. In case we are over the
 * memory limit, the function will try to free some memory to return back
 * under the limit.
 *
 * The function returns C_OK if we are under the memory limit or if we
 * were over the limit, but the attempt to free memory was successful.
 * Otehrwise if we are over the memory limit, but not enough memory
 * was freed to return back under the limit, the function returns C_ERR. *&#x2F;
int freeMemoryIfNeeded(void) &#123;
    int keys_freed &#x3D; 0;
    &#x2F;* By default replicas should ignore maxmemory
     * and just be masters exact copies. *&#x2F;
    if (server.masterhost &amp;&amp; server.repl_slave_ignore_maxmemory) return C_OK;

    size_t mem_reported, mem_tofree, mem_freed;
    mstime_t latency, eviction_latency;
    long long delta;
    int slaves &#x3D; listLength(server.slaves);

    &#x2F;* When clients are paused the dataset should be static not just from the
     * POV of clients not being able to write, but also from the POV of
     * expires and evictions of keys not being performed. *&#x2F;
    if (clientsArePaused()) return C_OK;
    if (getMaxmemoryState(&amp;mem_reported,NULL,&amp;mem_tofree,NULL) &#x3D;&#x3D; C_OK)
        return C_OK;

    mem_freed &#x3D; 0;

    if (server.maxmemory_policy &#x3D;&#x3D; MAXMEMORY_NO_EVICTION)
        goto cant_free; &#x2F;* We need to free memory, but policy forbids. *&#x2F;

    latencyStartMonitor(latency);
    while (mem_freed &lt; mem_tofree) &#123;
        int j, k, i;
        static unsigned int next_db &#x3D; 0;
        sds bestkey &#x3D; NULL;
        int bestdbid;
        redisDb *db;
        dict *dict;
        dictEntry *de;

        if (server.maxmemory_policy &amp; (MAXMEMORY_FLAG_LRU|MAXMEMORY_FLAG_LFU) ||
            server.maxmemory_policy &#x3D;&#x3D; MAXMEMORY_VOLATILE_TTL)
        &#123;
            struct evictionPoolEntry *pool &#x3D; EvictionPoolLRU;

            while(bestkey &#x3D;&#x3D; NULL) &#123;
                unsigned long total_keys &#x3D; 0, keys;

                &#x2F;* We don&#39;t want to make local-db choices when expiring keys,
                 * so to start populate the eviction pool sampling keys from
                 * every DB. *&#x2F;
                for (i &#x3D; 0; i &lt; server.dbnum; i++) &#123;
                    db &#x3D; server.db+i;
                    dict &#x3D; (server.maxmemory_policy &amp; MAXMEMORY_FLAG_ALLKEYS) ?
                            db-&gt;dict : db-&gt;expires;
                    if ((keys &#x3D; dictSize(dict)) !&#x3D; 0) &#123;
                        evictionPoolPopulate(i, dict, db-&gt;dict, pool);
                        total_keys +&#x3D; keys;
                    &#125;
                &#125;
                if (!total_keys) break; &#x2F;* No keys to evict. *&#x2F;

                &#x2F;* Go backward from best to worst element to evict. *&#x2F;
                for (k &#x3D; EVPOOL_SIZE-1; k &gt;&#x3D; 0; k--) &#123;
                    if (pool[k].key &#x3D;&#x3D; NULL) continue;
                    bestdbid &#x3D; pool[k].dbid;

                    if (server.maxmemory_policy &amp; MAXMEMORY_FLAG_ALLKEYS) &#123;
                        de &#x3D; dictFind(server.db[pool[k].dbid].dict,
                            pool[k].key);
                    &#125; else &#123;
                        de &#x3D; dictFind(server.db[pool[k].dbid].expires,
                            pool[k].key);
                    &#125;

                    &#x2F;* Remove the entry from the pool. *&#x2F;
                    if (pool[k].key !&#x3D; pool[k].cached)
                        sdsfree(pool[k].key);
                    pool[k].key &#x3D; NULL;
                    pool[k].idle &#x3D; 0;

                    &#x2F;* If the key exists, is our pick. Otherwise it is
                     * a ghost and we need to try the next element. *&#x2F;
                    if (de) &#123;
                        bestkey &#x3D; dictGetKey(de);
                        break;
                    &#125; else &#123;
                        &#x2F;* Ghost... Iterate again. *&#x2F;
                    &#125;
                &#125;
            &#125;
        &#125;

        &#x2F;* volatile-random and allkeys-random policy *&#x2F;
        else if (server.maxmemory_policy &#x3D;&#x3D; MAXMEMORY_ALLKEYS_RANDOM ||
                 server.maxmemory_policy &#x3D;&#x3D; MAXMEMORY_VOLATILE_RANDOM)
        &#123;
            &#x2F;* When evicting a random key, we try to evict a key for
             * each DB, so we use the static &#39;next_db&#39; variable to
             * incrementally visit all DBs. *&#x2F;
            for (i &#x3D; 0; i &lt; server.dbnum; i++) &#123;
                j &#x3D; (++next_db) % server.dbnum;
                db &#x3D; server.db+j;
                dict &#x3D; (server.maxmemory_policy &#x3D;&#x3D; MAXMEMORY_ALLKEYS_RANDOM) ?
                        db-&gt;dict : db-&gt;expires;
                if (dictSize(dict) !&#x3D; 0) &#123;
                    de &#x3D; dictGetRandomKey(dict);
                    bestkey &#x3D; dictGetKey(de);
                    bestdbid &#x3D; j;
                    break;
                &#125;
            &#125;
        &#125;

        &#x2F;* Finally remove the selected key. *&#x2F;
        if (bestkey) &#123;
            db &#x3D; server.db+bestdbid;
            robj *keyobj &#x3D; createStringObject(bestkey,sdslen(bestkey));
            propagateExpire(db,keyobj,server.lazyfree_lazy_eviction);
            &#x2F;* We compute the amount of memory freed by db*Delete() alone.
             * It is possible that actually the memory needed to propagate
             * the DEL in AOF and replication link is greater than the one
             * we are freeing removing the key, but we can&#39;t account for
             * that otherwise we would never exit the loop.
             *
             * AOF and Output buffer memory will be freed eventually so
             * we only care about memory used by the key space. *&#x2F;
            delta &#x3D; (long long) zmalloc_used_memory();
            latencyStartMonitor(eviction_latency);
            if (server.lazyfree_lazy_eviction)
                dbAsyncDelete(db,keyobj);
            else
                dbSyncDelete(db,keyobj);
            latencyEndMonitor(eviction_latency);
            latencyAddSampleIfNeeded(&quot;eviction-del&quot;,eviction_latency);
            latencyRemoveNestedEvent(latency,eviction_latency);
            delta -&#x3D; (long long) zmalloc_used_memory();
            mem_freed +&#x3D; delta;
            server.stat_evictedkeys++;
            notifyKeyspaceEvent(NOTIFY_EVICTED, &quot;evicted&quot;,
                keyobj, db-&gt;id);
            decrRefCount(keyobj);
            keys_freed++;

            &#x2F;* When the memory to free starts to be big enough, we may
             * start spending so much time here that is impossible to
             * deliver data to the slaves fast enough, so we force the
             * transmission here inside the loop. *&#x2F;
            if (slaves) flushSlavesOutputBuffers();

            &#x2F;* Normally our stop condition is the ability to release
             * a fixed, pre-computed amount of memory. However when we
             * are deleting objects in another thread, it&#39;s better to
             * check, from time to time, if we already reached our target
             * memory, since the &quot;mem_freed&quot; amount is computed only
             * across the dbAsyncDelete() call, while the thread can
             * release the memory all the time. *&#x2F;
            if (server.lazyfree_lazy_eviction &amp;&amp; !(keys_freed % 16)) &#123;
                if (getMaxmemoryState(NULL,NULL,NULL,NULL) &#x3D;&#x3D; C_OK) &#123;
                    &#x2F;* Let&#39;s satisfy our stop condition. *&#x2F;
                    mem_freed &#x3D; mem_tofree;
                &#125;
            &#125;
        &#125; else &#123;
            latencyEndMonitor(latency);
            latencyAddSampleIfNeeded(&quot;eviction-cycle&quot;,latency);
            goto cant_free; &#x2F;* nothing to free... *&#x2F;
        &#125;
    &#125;
    latencyEndMonitor(latency);
    latencyAddSampleIfNeeded(&quot;eviction-cycle&quot;,latency);
    return C_OK;

cant_free:
    &#x2F;* We are here if we are not able to reclaim memory. There is only one
     * last thing we can try: check if the lazyfree thread has jobs in queue
     * and wait... *&#x2F;
    while(bioPendingJobsOfType(BIO_LAZY_FREE)) &#123;
        if (((mem_reported - zmalloc_used_memory()) + mem_freed) &gt;&#x3D; mem_tofree)
            break;
        usleep(1000);
    &#125;
    return C_ERR;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这里就是根据具体策略去淘汰 key，首先是要往 pool 更新 key，更新key 的方法是<a href="https://github.com/antirez/redis/blob/unstable/src/evict.c#L162"><code>evictionPoolPopulate</code></a></p>
<pre class="line-numbers language-C" data-language="C"><code class="language-C">void evictionPoolPopulate(int dbid, dict *sampledict, dict *keydict, struct evictionPoolEntry *pool) &#123;
    int j, k, count;
    dictEntry *samples[server.maxmemory_samples];

    count &#x3D; dictGetSomeKeys(sampledict,samples,server.maxmemory_samples);
    for (j &#x3D; 0; j &lt; count; j++) &#123;
        unsigned long long idle;
        sds key;
        robj *o;
        dictEntry *de;

        de &#x3D; samples[j];
        key &#x3D; dictGetKey(de);

        &#x2F;* If the dictionary we are sampling from is not the main
         * dictionary (but the expires one) we need to lookup the key
         * again in the key dictionary to obtain the value object. *&#x2F;
        if (server.maxmemory_policy !&#x3D; MAXMEMORY_VOLATILE_TTL) &#123;
            if (sampledict !&#x3D; keydict) de &#x3D; dictFind(keydict, key);
            o &#x3D; dictGetVal(de);
        &#125;

        &#x2F;* Calculate the idle time according to the policy. This is called
         * idle just because the code initially handled LRU, but is in fact
         * just a score where an higher score means better candidate. *&#x2F;
        if (server.maxmemory_policy &amp; MAXMEMORY_FLAG_LRU) &#123;
            idle &#x3D; estimateObjectIdleTime(o);
        &#125; else if (server.maxmemory_policy &amp; MAXMEMORY_FLAG_LFU) &#123;
            &#x2F;* When we use an LRU policy, we sort the keys by idle time
             * so that we expire keys starting from greater idle time.
             * However when the policy is an LFU one, we have a frequency
             * estimation, and we want to evict keys with lower frequency
             * first. So inside the pool we put objects using the inverted
             * frequency subtracting the actual frequency to the maximum
             * frequency of 255. *&#x2F;
            idle &#x3D; 255-LFUDecrAndReturn(o);
        &#125; else if (server.maxmemory_policy &#x3D;&#x3D; MAXMEMORY_VOLATILE_TTL) &#123;
            &#x2F;* In this case the sooner the expire the better. *&#x2F;
            idle &#x3D; ULLONG_MAX - (long)dictGetVal(de);
        &#125; else &#123;
            serverPanic(&quot;Unknown eviction policy in evictionPoolPopulate()&quot;);
        &#125;

        &#x2F;* Insert the element inside the pool.
         * First, find the first empty bucket or the first populated
         * bucket that has an idle time smaller than our idle time. *&#x2F;
        k &#x3D; 0;
        while (k &lt; EVPOOL_SIZE &amp;&amp;
               pool[k].key &amp;&amp;
               pool[k].idle &lt; idle) k++;
        if (k &#x3D;&#x3D; 0 &amp;&amp; pool[EVPOOL_SIZE-1].key !&#x3D; NULL) &#123;
            &#x2F;* Can&#39;t insert if the element is &lt; the worst element we have
             * and there are no empty buckets. *&#x2F;
            continue;
        &#125; else if (k &lt; EVPOOL_SIZE &amp;&amp; pool[k].key &#x3D;&#x3D; NULL) &#123;
            &#x2F;* Inserting into empty position. No setup needed before insert. *&#x2F;
        &#125; else &#123;
            &#x2F;* Inserting in the middle. Now k points to the first element
             * greater than the element to insert.  *&#x2F;
            if (pool[EVPOOL_SIZE-1].key &#x3D;&#x3D; NULL) &#123;
                &#x2F;* Free space on the right? Insert at k shifting
                 * all the elements from k to end to the right. *&#x2F;

                &#x2F;* Save SDS before overwriting. *&#x2F;
                sds cached &#x3D; pool[EVPOOL_SIZE-1].cached;
                memmove(pool+k+1,pool+k,
                    sizeof(pool[0])*(EVPOOL_SIZE-k-1));
                pool[k].cached &#x3D; cached;
            &#125; else &#123;
                &#x2F;* No free space on right? Insert at k-1 *&#x2F;
                k--;
                &#x2F;* Shift all elements on the left of k (included) to the
                 * left, so we discard the element with smaller idle time. *&#x2F;
                sds cached &#x3D; pool[0].cached; &#x2F;* Save SDS before overwriting. *&#x2F;
                if (pool[0].key !&#x3D; pool[0].cached) sdsfree(pool[0].key);
                memmove(pool,pool+1,sizeof(pool[0])*k);
                pool[k].cached &#x3D; cached;
            &#125;
        &#125;

        &#x2F;* Try to reuse the cached SDS string allocated in the pool entry,
         * because allocating and deallocating this object is costly
         * (according to the profiler, not my fantasy. Remember:
         * premature optimizbla bla bla bla. *&#x2F;
        int klen &#x3D; sdslen(key);
        if (klen &gt; EVPOOL_CACHED_SDS_SIZE) &#123;
            pool[k].key &#x3D; sdsdup(key);
        &#125; else &#123;
            memcpy(pool[k].cached,key,klen+1);
            sdssetlen(pool[k].cached,klen);
            pool[k].key &#x3D; pool[k].cached;
        &#125;
        pool[k].idle &#x3D; idle;
        pool[k].dbid &#x3D; dbid;
    &#125;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><code>Redis</code>随机选择<code>maxmemory_samples</code>数量的key，然后计算这些<code>key</code>的空闲时间<code>idle time</code>，当满足条件时(比pool中的某些键的空闲时间还大)就可以进<code>pool</code>。<code>pool</code>更新之后，就淘汰<code>pool</code>中空闲时间最大的键。</p>
<p><a href="https://github.com/antirez/redis/blob/unstable/src/evict.c#L90"><code>estimateObjectIdleTime</code></a>用来计算Redis对象的空闲时间：</p>
<pre class="line-numbers language-C" data-language="C"><code class="language-C">&#x2F;* Given an object returns the min number of milliseconds the object was never
 * requested, using an approximated LRU algorithm. *&#x2F;
unsigned long long estimateObjectIdleTime(robj *o) &#123;
    unsigned long long lruclock &#x3D; LRU_CLOCK();
    if (lruclock &gt;&#x3D; o-&gt;lru) &#123;
        return (lruclock - o-&gt;lru) * LRU_CLOCK_RESOLUTION;
    &#125; else &#123;
        return (lruclock + (LRU_CLOCK_MAX - o-&gt;lru)) *
                    LRU_CLOCK_RESOLUTION;
    &#125;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>空闲时间第一种是 lurclock 大于对象的 lru，那么就是减一下乘以精度，因为 lruclock 有可能是已经预生成的，所以会可能走下面这个</p>
<h3 id="LFU"><a href="#LFU" class="headerlink" title="LFU"></a>LFU</h3><p>上面介绍了LRU 的算法，但是考虑一种场景</p>
<pre class="line-numbers language-none"><code class="language-none">~~~~~A~~~~~A~~~~~A~~~~A~~~~~A~~~~~A~~|
~~B~~B~~B~~B~~B~~B~~B~~B~~B~~B~~B~~B~|
~~~~~~~~~~C~~~~~~~~~C~~~~~~~~~C~~~~~~|
~~~~~D~~~~~~~~~~D~~~~~~~~~D~~~~~~~~~D|<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>可以发现，当采用 lru 的淘汰策略的时候，D 是最新的，会被认为是最值得保留的，但是事实上还不如 A 跟 B，然后 antirez 大神就想到了LFU (Least Frequently Used) 这个算法, 显然对于上面的四个 key 的访问频率，保留优先级应该是 B &gt; A &gt; C = D<br>那要怎么来实现这个 LFU 算法呢，其实像LRU，理想的情况就是维护个链表，把最新访问的放到头上去，但是这个会影响访问速度，注意到前面代码的应该可以看到，redisObject 的 lru 字段其实是两用的，当策略是 LFU 时，这个字段就另作他用了，它的 24 位长度被分成两部分</p>
<pre class="line-numbers language-none"><code class="language-none">      16 bits      8 bits
+----------------+--------+
+ Last decr time | LOG_C  |
+----------------+--------+<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>前16位字段是最后一次递减时间，因此Redis知道 上一次计数器递减，后8位是 计数器 counter。<br>LFU 的主体策略就是当这个 key 被访问的次数越多频率越高他就越容易被保留下来，并且是最近被访问的频率越高。这其实有两个事情要做，一个是在访问的时候增加计数值，在一定长时间不访问时进行衰减，所以这里用了两个值，前 16 位记录上一次衰减的时间，后 8 位记录具体的计数值。<br>Redis4.0之后为maxmemory_policy淘汰策略添加了两个LFU模式：</p>
<p><code>volatile-lfu</code>：对有过期时间的key采用LFU淘汰策略<br><code>allkeys-lfu</code>：对全部key采用LFU淘汰策略<br>还有2个配置可以调整LFU算法：  </p>
<pre class="line-numbers language-none"><code class="language-none">lfu-log-factor 10
lfu-decay-time 1
&#96;&#96;&#96;  
&#96;lfu-log-factor&#96; 可以调整计数器counter的增长速度，lfu-log-factor越大，counter增长的越慢。

&#96;lfu-decay-time&#96;是一个以分钟为单位的数值，可以调整counter的减少速度
这里有个问题是 8 位大小够计么，访问一次加 1 的话的确不够，不过大神就是大神，才不会这么简单的加一。往下看代码
&#96;&#96;&#96;C
&#x2F;* Low level key lookup API, not actually called directly from commands
 * implementations that should instead rely on lookupKeyRead(),
 * lookupKeyWrite() and lookupKeyReadWithFlags(). *&#x2F;
robj *lookupKey(redisDb *db, robj *key, int flags) &#123;
    dictEntry *de &#x3D; dictFind(db-&gt;dict,key-&gt;ptr);
    if (de) &#123;
        robj *val &#x3D; dictGetVal(de);

        &#x2F;* Update the access time for the ageing algorithm.
         * Don&#39;t do it if we have a saving child, as this will trigger
         * a copy on write madness. *&#x2F;
        if (!hasActiveChildProcess() &amp;&amp; !(flags &amp; LOOKUP_NOTOUCH))&#123;
            if (server.maxmemory_policy &amp; MAXMEMORY_FLAG_LFU) &#123;
                &#x2F;&#x2F; 当淘汰策略是 LFU 时，就会调用这个updateLFU
                updateLFU(val);
            &#125; else &#123;
                val-&gt;lru &#x3D; LRU_CLOCK();
            &#125;
        &#125;
        return val;
    &#125; else &#123;
        return NULL;
    &#125;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><a href="https://github.com/antirez/redis/blob/unstable/src/db.c#L46"><code>updateLFU</code></a> 这个其实个入口，调用了两个重要的方法</p>
<pre class="line-numbers language-C" data-language="C"><code class="language-C">&#x2F;* Update LFU when an object is accessed.
 * Firstly, decrement the counter if the decrement time is reached.
 * Then logarithmically increment the counter, and update the access time. *&#x2F;
void updateLFU(robj *val) &#123;
    unsigned long counter &#x3D; LFUDecrAndReturn(val);
    counter &#x3D; LFULogIncr(counter);
    val-&gt;lru &#x3D; (LFUGetTimeInMinutes()&lt;&lt;8) | counter;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>首先来看看<a href="https://github.com/antirez/redis/blob/unstable/src/evict.c#L335"><code>LFUDecrAndReturn</code></a>，这个方法的作用是根据上一次衰减时间和系统配置的 <code>lfu-decay-time</code> 参数来确定需要将 counter 减去多少</p>
<pre class="line-numbers language-C" data-language="C"><code class="language-C">&#x2F;* If the object decrement time is reached decrement the LFU counter but
 * do not update LFU fields of the object, we update the access time
 * and counter in an explicit way when the object is really accessed.
 * And we will times halve the counter according to the times of
 * elapsed time than server.lfu_decay_time.
 * Return the object frequency counter.
 *
 * This function is used in order to scan the dataset for the best object
 * to fit: as we check for the candidate, we incrementally decrement the
 * counter of the scanned objects if needed. *&#x2F;
unsigned long LFUDecrAndReturn(robj *o) &#123;
    &#x2F;&#x2F; 右移 8 位，拿到上次衰减时间
    unsigned long ldt &#x3D; o-&gt;lru &gt;&gt; 8;
    &#x2F;&#x2F; 对 255 做与操作，拿到 counter 值
    unsigned long counter &#x3D; o-&gt;lru &amp; 255;
    &#x2F;&#x2F; 根据lfu_decay_time来算出过了多少个衰减周期
    unsigned long num_periods &#x3D; server.lfu_decay_time ? LFUTimeElapsed(ldt) &#x2F; server.lfu_decay_time : 0;
    if (num_periods)
        counter &#x3D; (num_periods &gt; counter) ? 0 : counter - num_periods;
    return counter;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>然后是加，调用了<a href="https://github.com/antirez/redis/blob/unstable/src/evict.c#L315"><code>LFULogIncr</code></a></p>
<pre class="line-numbers language-C" data-language="C"><code class="language-C">&#x2F;* Logarithmically increment a counter. The greater is the current counter value
 * the less likely is that it gets really implemented. Saturate it at 255. *&#x2F;
uint8_t LFULogIncr(uint8_t counter) &#123;
    &#x2F;&#x2F; 最大值就是 255，到顶了就不加了
    if (counter &#x3D;&#x3D; 255) return 255;
    &#x2F;&#x2F; 生成个随机小数
    double r &#x3D; (double)rand()&#x2F;RAND_MAX;
    &#x2F;&#x2F; 减去个基础值，LFU_INIT_VAL &#x3D; 5，防止刚进来就被逐出
    double baseval &#x3D; counter - LFU_INIT_VAL;
    &#x2F;&#x2F; 如果是小于 0，
    if (baseval &lt; 0) baseval &#x3D; 0;
    &#x2F;&#x2F; 如果 baseval 是 0，那么 p 就是 1了，后面 counter 直接加一，如果不是的话，得看系统参数lfu_log_factor，这个越大，除出来的 p 越小，那么 counter++的可能性也越小，这样子就把前面的疑问给解决了，不是直接+1 的
    double p &#x3D; 1.0&#x2F;(baseval*server.lfu_log_factor+1);
    if (r &lt; p) counter++;
    return counter;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>大概的变化速度可以参考</p>
<pre class="line-numbers language-none"><code class="language-none">+--------+------------+------------+------------+------------+------------+
| factor | 100 hits   | 1000 hits  | 100K hits  | 1M hits    | 10M hits   |
+--------+------------+------------+------------+------------+------------+
| 0      | 104        | 255        | 255        | 255        | 255        |
+--------+------------+------------+------------+------------+------------+
| 1      | 18         | 49         | 255        | 255        | 255        |
+--------+------------+------------+------------+------------+------------+
| 10     | 10         | 18         | 142        | 255        | 255        |
+--------+------------+------------+------------+------------+------------+
| 100    | 8          | 11         | 49         | 143        | 255        |
+--------+------------+------------+------------+------------+------------+<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>简而言之就是 lfu_log_factor 越大变化的越慢</p>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>总结一下，redis 实现了近似的 lru 淘汰策略，通过增加了淘汰 key 的池子(pool)，并且增大每次抽样的 key 的数量来将淘汰效果更进一步地接近于 lru，这是 lru 策略，但是对于前面举的一个例子，其实 lru 并不能保证 key 的淘汰就如我们预期，所以在后期又引入了 lfu 的策略，lfu的策略比较巧妙，复用了 redis 对象的 lru 字段，并且使用了factor 参数来控制计数器递增的速度，防止 8 位的计数器太早溢出。</p>
]]></content>
      <categories>
        <category>Redis</category>
        <category>数据结构</category>
        <category>C</category>
        <category>源码</category>
        <category>Redis</category>
      </categories>
      <tags>
        <tag>redis</tag>
        <tag>数据结构</tag>
        <tag>源码</tag>
      </tags>
  </entry>
  <entry>
    <title>聊一下 RocketMQ 的 NameServer 源码</title>
    <url>/2020/07/05/%E8%81%8A%E4%B8%80%E4%B8%8B-RocketMQ-%E7%9A%84-NameServer-%E6%BA%90%E7%A0%81/</url>
    <content><![CDATA[<p>前面介绍了，nameserver相当于dubbo的注册中心，用与管理broker，broker会在启动的时候注册到nameserver，并且会发送心跳给namaserver，nameserver负责保存活跃的broker，包括master和slave，同时保存topic和topic下的队列，以及filter列表，然后为producer和consumer的请求提供服务。</p>
<h3 id="启动过程"><a href="#启动过程" class="headerlink" title="启动过程"></a>启动过程</h3><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token function">main0</span><span class="token punctuation">(</span>args<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token class-name">NamesrvController</span> <span class="token function">main0</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>

        <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">NamesrvController</span> controller <span class="token operator">=</span> <span class="token function">createNamesrvController</span><span class="token punctuation">(</span>args<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token function">start</span><span class="token punctuation">(</span>controller<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">String</span> tip <span class="token operator">=</span> <span class="token string">"The Name Server boot success. serializeType="</span> <span class="token operator">+</span> <span class="token class-name">RemotingCommand</span><span class="token punctuation">.</span><span class="token function">getSerializeTypeConfigInThisServer</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span>tip<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"%s%n"</span><span class="token punctuation">,</span> tip<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">return</span> controller<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Throwable</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">exit</span><span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">return</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>入口的代码时这样子，其实主要的逻辑在createNamesrvController和start方法，来看下这两个的实现</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token class-name">NamesrvController</span> <span class="token function">createNamesrvController</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">IOException</span><span class="token punctuation">,</span> <span class="token class-name">JoranException</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">setProperty</span><span class="token punctuation">(</span><span class="token class-name">RemotingCommand</span><span class="token punctuation">.</span>REMOTING_VERSION_KEY<span class="token punctuation">,</span> <span class="token class-name">Integer</span><span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token class-name">MQVersion</span><span class="token punctuation">.</span>CURRENT_VERSION<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">//PackageConflictDetect.detectFastjson();</span>

        <span class="token class-name">Options</span> options <span class="token operator">=</span> <span class="token class-name">ServerUtil</span><span class="token punctuation">.</span><span class="token function">buildCommandlineOptions</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Options</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        commandLine <span class="token operator">=</span> <span class="token class-name">ServerUtil</span><span class="token punctuation">.</span><span class="token function">parseCmdLine</span><span class="token punctuation">(</span><span class="token string">"mqnamesrv"</span><span class="token punctuation">,</span> args<span class="token punctuation">,</span> <span class="token function">buildCommandlineOptions</span><span class="token punctuation">(</span>options<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">PosixParser</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">null</span> <span class="token operator">==</span> commandLine<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">exit</span><span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">return</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">final</span> <span class="token class-name">NamesrvConfig</span> namesrvConfig <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">NamesrvConfig</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">final</span> <span class="token class-name">NettyServerConfig</span> nettyServerConfig <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">NettyServerConfig</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        nettyServerConfig<span class="token punctuation">.</span><span class="token function">setListenPort</span><span class="token punctuation">(</span><span class="token number">9876</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>commandLine<span class="token punctuation">.</span><span class="token function">hasOption</span><span class="token punctuation">(</span><span class="token string">'c'</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">String</span> file <span class="token operator">=</span> commandLine<span class="token punctuation">.</span><span class="token function">getOptionValue</span><span class="token punctuation">(</span><span class="token string">'c'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>file <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token class-name">InputStream</span> in <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">BufferedInputStream</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">FileInputStream</span><span class="token punctuation">(</span>file<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                properties <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Properties</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                properties<span class="token punctuation">.</span><span class="token function">load</span><span class="token punctuation">(</span>in<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token class-name">MixAll</span><span class="token punctuation">.</span><span class="token function">properties2Object</span><span class="token punctuation">(</span>properties<span class="token punctuation">,</span> namesrvConfig<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token class-name">MixAll</span><span class="token punctuation">.</span><span class="token function">properties2Object</span><span class="token punctuation">(</span>properties<span class="token punctuation">,</span> nettyServerConfig<span class="token punctuation">)</span><span class="token punctuation">;</span>

                namesrvConfig<span class="token punctuation">.</span><span class="token function">setConfigStorePath</span><span class="token punctuation">(</span>file<span class="token punctuation">)</span><span class="token punctuation">;</span>

                <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"load config properties file OK, %s%n"</span><span class="token punctuation">,</span> file<span class="token punctuation">)</span><span class="token punctuation">;</span>
                in<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span>commandLine<span class="token punctuation">.</span><span class="token function">hasOption</span><span class="token punctuation">(</span><span class="token string">'p'</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">InternalLogger</span> console <span class="token operator">=</span> <span class="token class-name">InternalLoggerFactory</span><span class="token punctuation">.</span><span class="token function">getLogger</span><span class="token punctuation">(</span><span class="token class-name">LoggerName</span><span class="token punctuation">.</span>NAMESRV_CONSOLE_NAME<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">MixAll</span><span class="token punctuation">.</span><span class="token function">printObjectProperties</span><span class="token punctuation">(</span>console<span class="token punctuation">,</span> namesrvConfig<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">MixAll</span><span class="token punctuation">.</span><span class="token function">printObjectProperties</span><span class="token punctuation">(</span>console<span class="token punctuation">,</span> nettyServerConfig<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">exit</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token class-name">MixAll</span><span class="token punctuation">.</span><span class="token function">properties2Object</span><span class="token punctuation">(</span><span class="token class-name">ServerUtil</span><span class="token punctuation">.</span><span class="token function">commandLine2Properties</span><span class="token punctuation">(</span>commandLine<span class="token punctuation">)</span><span class="token punctuation">,</span> namesrvConfig<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">null</span> <span class="token operator">==</span> namesrvConfig<span class="token punctuation">.</span><span class="token function">getRocketmqHome</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">printf</span><span class="token punctuation">(</span><span class="token string">"Please set the %s variable in your environment to match the location of the RocketMQ installation%n"</span><span class="token punctuation">,</span> <span class="token class-name">MixAll</span><span class="token punctuation">.</span>ROCKETMQ_HOME_ENV<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">exit</span><span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token class-name">LoggerContext</span> lc <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">LoggerContext</span><span class="token punctuation">)</span> <span class="token class-name">LoggerFactory</span><span class="token punctuation">.</span><span class="token function">getILoggerFactory</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">JoranConfigurator</span> configurator <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">JoranConfigurator</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        configurator<span class="token punctuation">.</span><span class="token function">setContext</span><span class="token punctuation">(</span>lc<span class="token punctuation">)</span><span class="token punctuation">;</span>
        lc<span class="token punctuation">.</span><span class="token function">reset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        configurator<span class="token punctuation">.</span><span class="token function">doConfigure</span><span class="token punctuation">(</span>namesrvConfig<span class="token punctuation">.</span><span class="token function">getRocketmqHome</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">"/conf/logback_namesrv.xml"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        log <span class="token operator">=</span> <span class="token class-name">InternalLoggerFactory</span><span class="token punctuation">.</span><span class="token function">getLogger</span><span class="token punctuation">(</span><span class="token class-name">LoggerName</span><span class="token punctuation">.</span>NAMESRV_LOGGER_NAME<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token class-name">MixAll</span><span class="token punctuation">.</span><span class="token function">printObjectProperties</span><span class="token punctuation">(</span>log<span class="token punctuation">,</span> namesrvConfig<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">MixAll</span><span class="token punctuation">.</span><span class="token function">printObjectProperties</span><span class="token punctuation">(</span>log<span class="token punctuation">,</span> nettyServerConfig<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">final</span> <span class="token class-name">NamesrvController</span> controller <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">NamesrvController</span><span class="token punctuation">(</span>namesrvConfig<span class="token punctuation">,</span> nettyServerConfig<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment">// remember all configs to prevent discard</span>
        controller<span class="token punctuation">.</span><span class="token function">getConfiguration</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">registerConfig</span><span class="token punctuation">(</span>properties<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">return</span> controller<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>这个方法里其实主要是读取一些配置啥的，不是很复杂，</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token class-name">NamesrvController</span> <span class="token function">start</span><span class="token punctuation">(</span><span class="token keyword">final</span> <span class="token class-name">NamesrvController</span> controller<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">Exception</span> <span class="token punctuation">&#123;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">null</span> <span class="token operator">==</span> controller<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">IllegalArgumentException</span><span class="token punctuation">(</span><span class="token string">"NamesrvController is null"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">boolean</span> initResult <span class="token operator">=</span> controller<span class="token punctuation">.</span><span class="token function">initialize</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>initResult<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            controller<span class="token punctuation">.</span><span class="token function">shutdown</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">exit</span><span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token class-name">Runtime</span><span class="token punctuation">.</span><span class="token function">getRuntime</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">addShutdownHook</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">ShutdownHookThread</span><span class="token punctuation">(</span>log<span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">Callable</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Void</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token annotation punctuation">@Override</span>
            <span class="token keyword">public</span> <span class="token class-name">Void</span> <span class="token function">call</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">Exception</span> <span class="token punctuation">&#123;</span>
                controller<span class="token punctuation">.</span><span class="token function">shutdown</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">return</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        controller<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">return</span> controller<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>这个start里主要关注initialize方法，后面就是一个停机的hook，来看下initialize方法</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">initialize</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>

        <span class="token keyword">this</span><span class="token punctuation">.</span>kvConfigManager<span class="token punctuation">.</span><span class="token function">load</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">this</span><span class="token punctuation">.</span>remotingServer <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">NettyRemotingServer</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>nettyServerConfig<span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>brokerHousekeepingService<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">this</span><span class="token punctuation">.</span>remotingExecutor <span class="token operator">=</span>
            <span class="token class-name">Executors</span><span class="token punctuation">.</span><span class="token function">newFixedThreadPool</span><span class="token punctuation">(</span>nettyServerConfig<span class="token punctuation">.</span><span class="token function">getServerWorkerThreads</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">ThreadFactoryImpl</span><span class="token punctuation">(</span><span class="token string">"RemotingExecutorThread_"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">registerProcessor</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">this</span><span class="token punctuation">.</span>scheduledExecutorService<span class="token punctuation">.</span><span class="token function">scheduleAtFixedRate</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Runnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>

            <span class="token annotation punctuation">@Override</span>
            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token class-name">NamesrvController</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>routeInfoManager<span class="token punctuation">.</span><span class="token function">scanNotActiveBroker</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">,</span> <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>SECONDS<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">this</span><span class="token punctuation">.</span>scheduledExecutorService<span class="token punctuation">.</span><span class="token function">scheduleAtFixedRate</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Runnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>

            <span class="token annotation punctuation">@Override</span>
            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token class-name">NamesrvController</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>kvConfigManager<span class="token punctuation">.</span><span class="token function">printAllPeriodically</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">,</span> <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>MINUTES<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">TlsSystemConfig</span><span class="token punctuation">.</span>tlsMode <span class="token operator">!=</span> <span class="token class-name">TlsMode</span><span class="token punctuation">.</span>DISABLED<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token comment">// Register a listener to reload SslContext</span>
            <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                fileWatchService <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">FileWatchService</span><span class="token punctuation">(</span>
                    <span class="token keyword">new</span> <span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token punctuation">&#123;</span>
                        <span class="token class-name">TlsSystemConfig</span><span class="token punctuation">.</span>tlsServerCertPath<span class="token punctuation">,</span>
                        <span class="token class-name">TlsSystemConfig</span><span class="token punctuation">.</span>tlsServerKeyPath<span class="token punctuation">,</span>
                        <span class="token class-name">TlsSystemConfig</span><span class="token punctuation">.</span>tlsServerTrustCertPath
                    <span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
                    <span class="token keyword">new</span> <span class="token class-name">FileWatchService<span class="token punctuation">.</span>Listener</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        <span class="token keyword">boolean</span> certChanged<span class="token punctuation">,</span> keyChanged <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
                        <span class="token annotation punctuation">@Override</span>
                        <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">onChanged</span><span class="token punctuation">(</span><span class="token class-name">String</span> path<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                            <span class="token keyword">if</span> <span class="token punctuation">(</span>path<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span><span class="token class-name">TlsSystemConfig</span><span class="token punctuation">.</span>tlsServerTrustCertPath<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"The trust certificate changed, reload the ssl context"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                                <span class="token function">reloadServerSslContext</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token punctuation">&#125;</span>
                            <span class="token keyword">if</span> <span class="token punctuation">(</span>path<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span><span class="token class-name">TlsSystemConfig</span><span class="token punctuation">.</span>tlsServerCertPath<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                certChanged <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
                            <span class="token punctuation">&#125;</span>
                            <span class="token keyword">if</span> <span class="token punctuation">(</span>path<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span><span class="token class-name">TlsSystemConfig</span><span class="token punctuation">.</span>tlsServerKeyPath<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                keyChanged <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
                            <span class="token punctuation">&#125;</span>
                            <span class="token keyword">if</span> <span class="token punctuation">(</span>certChanged <span class="token operator">&amp;&amp;</span> keyChanged<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"The certificate and private key changed, reload the ssl context"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                                certChanged <span class="token operator">=</span> keyChanged <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
                                <span class="token function">reloadServerSslContext</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token punctuation">&#125;</span>
                        <span class="token punctuation">&#125;</span>
                        <span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">reloadServerSslContext</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                            <span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token class-name">NettyRemotingServer</span><span class="token punctuation">)</span> remotingServer<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">loadSslContext</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token punctuation">&#125;</span>
                    <span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token string">"FileWatchService created error, can't load the certificate dynamically"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>这里的kvConfigManager主要是来加载NameServer的配置参数，存到org.apache.rocketmq.namesrv.kvconfig.KVConfigManager#configTable中，然后是以BrokerHousekeepingService对象为参数初始化NettyRemotingServer对象，BrokerHousekeepingService对象作为该Netty连接中Socket链接的监听器（ChannelEventListener）；监听与Broker建立的渠道的状态（空闲、关闭、异常三个状态），并调用BrokerHousekeepingService的相应onChannel方法。其中渠道的空闲、关闭、异常状态均调用RouteInfoManager.onChannelDestory方法处理。这个BrokerHousekeepingService可以字面化地理解为broker的管家服务，这个类内部三个状态方法其实都是调用的org.apache.rocketmq.namesrv.NamesrvController#getRouteInfoManager方法，而这个RouteInfoManager里面的对象有这些</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">RouteInfoManager</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">final</span> <span class="token class-name">InternalLogger</span> log <span class="token operator">=</span> <span class="token class-name">InternalLoggerFactory</span><span class="token punctuation">.</span><span class="token function">getLogger</span><span class="token punctuation">(</span><span class="token class-name">LoggerName</span><span class="token punctuation">.</span>NAMESRV_LOGGER_NAME<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token keyword">static</span> <span class="token keyword">long</span> BROKER_CHANNEL_EXPIRED_TIME <span class="token operator">=</span> <span class="token number">1000</span> <span class="token operator">*</span> <span class="token number">60</span> <span class="token operator">*</span> <span class="token number">2</span><span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token class-name">ReadWriteLock</span> lock <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ReentrantReadWriteLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token comment">// topic与queue的对应关系</span>
    <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token class-name">HashMap</span><span class="token operator">&lt;</span><span class="token class-name">String</span><span class="token comment">/* topic */</span><span class="token punctuation">,</span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">QueueData</span><span class="token punctuation">></span></span><span class="token operator">></span> topicQueueTable<span class="token punctuation">;</span>
  <span class="token comment">// Broker名称与broker属性的map</span>
    <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token class-name">HashMap</span><span class="token operator">&lt;</span><span class="token class-name">String</span><span class="token comment">/* brokerName */</span><span class="token punctuation">,</span> <span class="token class-name">BrokerData</span><span class="token operator">></span> brokerAddrTable<span class="token punctuation">;</span>
  <span class="token comment">// 集群与broker集合的对应关系</span>
    <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token class-name">HashMap</span><span class="token operator">&lt;</span><span class="token class-name">String</span><span class="token comment">/* clusterName */</span><span class="token punctuation">,</span> <span class="token class-name">Set</span><span class="token operator">&lt;</span><span class="token class-name">String</span><span class="token comment">/* brokerName */</span><span class="token operator">>></span> clusterAddrTable<span class="token punctuation">;</span>
  <span class="token comment">// 活跃的broker信息</span>
    <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token class-name">HashMap</span><span class="token operator">&lt;</span><span class="token class-name">String</span><span class="token comment">/* brokerAddr */</span><span class="token punctuation">,</span> <span class="token class-name">BrokerLiveInfo</span><span class="token operator">></span> brokerLiveTable<span class="token punctuation">;</span>
  <span class="token comment">// Broker地址与过滤器</span>
    <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token class-name">HashMap</span><span class="token operator">&lt;</span><span class="token class-name">String</span><span class="token comment">/* brokerAddr */</span><span class="token punctuation">,</span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">></span></span><span class="token comment">/* Filter Server */</span><span class="token operator">></span> filterServerTable<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>然后接下去就是初始化了一个线程池，然后注册默认的处理类<code>this.registerProcessor();</code>默认都是这个处理器去处理请求 <code>org.apache.rocketmq.namesrv.processor.DefaultRequestProcessor#DefaultRequestProcessor</code>然后是初始化两个定时任务</p>
<p>第一是每10秒检查一遍Broker的状态的定时任务，调用scanNotActiveBroker方法；遍历brokerLiveTable集合，查看每个broker的最后更新时间（BrokerLiveInfo.lastUpdateTimestamp）是否超过2分钟，若超过则关闭该broker的渠道并调用RouteInfoManager.onChannelDestory方法清理RouteInfoManager类的topicQueueTable、brokerAddrTable、clusterAddrTable、filterServerTable成员变量。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">this</span><span class="token punctuation">.</span>scheduledExecutorService<span class="token punctuation">.</span><span class="token function">scheduleAtFixedRate</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Runnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>

            <span class="token annotation punctuation">@Override</span>
            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token class-name">NamesrvController</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>routeInfoManager<span class="token punctuation">.</span><span class="token function">scanNotActiveBroker</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">,</span> <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>SECONDS<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">scanNotActiveBroker</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">Iterator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Entry</span><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">BrokerLiveInfo</span><span class="token punctuation">></span><span class="token punctuation">></span></span> it <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>brokerLiveTable<span class="token punctuation">.</span><span class="token function">entrySet</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">iterator</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">while</span> <span class="token punctuation">(</span>it<span class="token punctuation">.</span><span class="token function">hasNext</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">Entry</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">BrokerLiveInfo</span><span class="token punctuation">></span></span> next <span class="token operator">=</span> it<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">long</span> last <span class="token operator">=</span> next<span class="token punctuation">.</span><span class="token function">getValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getLastUpdateTimestamp</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token punctuation">(</span>last <span class="token operator">+</span> BROKER_CHANNEL_EXPIRED_TIME<span class="token punctuation">)</span> <span class="token operator">&lt;</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">currentTimeMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token class-name">RemotingUtil</span><span class="token punctuation">.</span><span class="token function">closeChannel</span><span class="token punctuation">(</span>next<span class="token punctuation">.</span><span class="token function">getValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getChannel</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                it<span class="token punctuation">.</span><span class="token function">remove</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token string">"The broker channel expired, &#123;&#125; &#123;&#125;ms"</span><span class="token punctuation">,</span> next<span class="token punctuation">.</span><span class="token function">getKey</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> BROKER_CHANNEL_EXPIRED_TIME<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">onChannelDestroy</span><span class="token punctuation">(</span>next<span class="token punctuation">.</span><span class="token function">getKey</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> next<span class="token punctuation">.</span><span class="token function">getValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getChannel</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">onChannelDestroy</span><span class="token punctuation">(</span><span class="token class-name">String</span> remoteAddr<span class="token punctuation">,</span> <span class="token class-name">Channel</span> channel<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">String</span> brokerAddrFound <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>channel <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">this</span><span class="token punctuation">.</span>lock<span class="token punctuation">.</span><span class="token function">readLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">lockInterruptibly</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token class-name">Iterator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Entry</span><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">BrokerLiveInfo</span><span class="token punctuation">></span><span class="token punctuation">></span></span> itBrokerLiveTable <span class="token operator">=</span>
                        <span class="token keyword">this</span><span class="token punctuation">.</span>brokerLiveTable<span class="token punctuation">.</span><span class="token function">entrySet</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">iterator</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">while</span> <span class="token punctuation">(</span>itBrokerLiveTable<span class="token punctuation">.</span><span class="token function">hasNext</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        <span class="token class-name">Entry</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">BrokerLiveInfo</span><span class="token punctuation">></span></span> entry <span class="token operator">=</span> itBrokerLiveTable<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token keyword">if</span> <span class="token punctuation">(</span>entry<span class="token punctuation">.</span><span class="token function">getValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getChannel</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> channel<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                            brokerAddrFound <span class="token operator">=</span> entry<span class="token punctuation">.</span><span class="token function">getKey</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token keyword">break</span><span class="token punctuation">;</span>
                        <span class="token punctuation">&#125;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">finally</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">this</span><span class="token punctuation">.</span>lock<span class="token punctuation">.</span><span class="token function">readLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"onChannelDestroy Exception"</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">null</span> <span class="token operator">==</span> brokerAddrFound<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            brokerAddrFound <span class="token operator">=</span> remoteAddr<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
            log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"the broker's channel destroyed, &#123;&#125;, clean it's data structure at once"</span><span class="token punctuation">,</span> brokerAddrFound<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span>brokerAddrFound <span class="token operator">!=</span> <span class="token keyword">null</span> <span class="token operator">&amp;&amp;</span> brokerAddrFound<span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">></span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>

            <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">this</span><span class="token punctuation">.</span>lock<span class="token punctuation">.</span><span class="token function">writeLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">lockInterruptibly</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">this</span><span class="token punctuation">.</span>brokerLiveTable<span class="token punctuation">.</span><span class="token function">remove</span><span class="token punctuation">(</span>brokerAddrFound<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">this</span><span class="token punctuation">.</span>filterServerTable<span class="token punctuation">.</span><span class="token function">remove</span><span class="token punctuation">(</span>brokerAddrFound<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token class-name">String</span> brokerNameFound <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
                    <span class="token keyword">boolean</span> removeBrokerName <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
                    <span class="token class-name">Iterator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Entry</span><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">BrokerData</span><span class="token punctuation">></span><span class="token punctuation">></span></span> itBrokerAddrTable <span class="token operator">=</span>
                        <span class="token keyword">this</span><span class="token punctuation">.</span>brokerAddrTable<span class="token punctuation">.</span><span class="token function">entrySet</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">iterator</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">while</span> <span class="token punctuation">(</span>itBrokerAddrTable<span class="token punctuation">.</span><span class="token function">hasNext</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> <span class="token punctuation">(</span><span class="token keyword">null</span> <span class="token operator">==</span> brokerNameFound<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        <span class="token class-name">BrokerData</span> brokerData <span class="token operator">=</span> itBrokerAddrTable<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

                        <span class="token class-name">Iterator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Entry</span><span class="token punctuation">&lt;</span><span class="token class-name">Long</span><span class="token punctuation">,</span> <span class="token class-name">String</span><span class="token punctuation">></span><span class="token punctuation">></span></span> it <span class="token operator">=</span> brokerData<span class="token punctuation">.</span><span class="token function">getBrokerAddrs</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">entrySet</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">iterator</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token keyword">while</span> <span class="token punctuation">(</span>it<span class="token punctuation">.</span><span class="token function">hasNext</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                            <span class="token class-name">Entry</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Long</span><span class="token punctuation">,</span> <span class="token class-name">String</span><span class="token punctuation">></span></span> entry <span class="token operator">=</span> it<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token class-name">Long</span> brokerId <span class="token operator">=</span> entry<span class="token punctuation">.</span><span class="token function">getKey</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token class-name">String</span> brokerAddr <span class="token operator">=</span> entry<span class="token punctuation">.</span><span class="token function">getValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token keyword">if</span> <span class="token punctuation">(</span>brokerAddr<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>brokerAddrFound<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                brokerNameFound <span class="token operator">=</span> brokerData<span class="token punctuation">.</span><span class="token function">getBrokerName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                                it<span class="token punctuation">.</span><span class="token function">remove</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                                log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"remove brokerAddr[&#123;&#125;, &#123;&#125;] from brokerAddrTable, because channel destroyed"</span><span class="token punctuation">,</span>
                                    brokerId<span class="token punctuation">,</span> brokerAddr<span class="token punctuation">)</span><span class="token punctuation">;</span>
                                <span class="token keyword">break</span><span class="token punctuation">;</span>
                            <span class="token punctuation">&#125;</span>
                        <span class="token punctuation">&#125;</span>

                        <span class="token keyword">if</span> <span class="token punctuation">(</span>brokerData<span class="token punctuation">.</span><span class="token function">getBrokerAddrs</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">isEmpty</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                            removeBrokerName <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
                            itBrokerAddrTable<span class="token punctuation">.</span><span class="token function">remove</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                            log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"remove brokerName[&#123;&#125;] from brokerAddrTable, because channel destroyed"</span><span class="token punctuation">,</span>
                                brokerData<span class="token punctuation">.</span><span class="token function">getBrokerName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token punctuation">&#125;</span>
                    <span class="token punctuation">&#125;</span>

                    <span class="token keyword">if</span> <span class="token punctuation">(</span>brokerNameFound <span class="token operator">!=</span> <span class="token keyword">null</span> <span class="token operator">&amp;&amp;</span> removeBrokerName<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        <span class="token class-name">Iterator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Entry</span><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">Set</span><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">></span><span class="token punctuation">></span><span class="token punctuation">></span></span> it <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>clusterAddrTable<span class="token punctuation">.</span><span class="token function">entrySet</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">iterator</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token keyword">while</span> <span class="token punctuation">(</span>it<span class="token punctuation">.</span><span class="token function">hasNext</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                            <span class="token class-name">Entry</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">Set</span><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">></span><span class="token punctuation">></span></span> entry <span class="token operator">=</span> it<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token class-name">String</span> clusterName <span class="token operator">=</span> entry<span class="token punctuation">.</span><span class="token function">getKey</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token class-name">Set</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">></span></span> brokerNames <span class="token operator">=</span> entry<span class="token punctuation">.</span><span class="token function">getValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token keyword">boolean</span> removed <span class="token operator">=</span> brokerNames<span class="token punctuation">.</span><span class="token function">remove</span><span class="token punctuation">(</span>brokerNameFound<span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token keyword">if</span> <span class="token punctuation">(</span>removed<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"remove brokerName[&#123;&#125;], clusterName[&#123;&#125;] from clusterAddrTable, because channel destroyed"</span><span class="token punctuation">,</span>
                                    brokerNameFound<span class="token punctuation">,</span> clusterName<span class="token punctuation">)</span><span class="token punctuation">;</span>

                                <span class="token keyword">if</span> <span class="token punctuation">(</span>brokerNames<span class="token punctuation">.</span><span class="token function">isEmpty</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                    log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"remove the clusterName[&#123;&#125;] from clusterAddrTable, because channel destroyed and no broker in this cluster"</span><span class="token punctuation">,</span>
                                        clusterName<span class="token punctuation">)</span><span class="token punctuation">;</span>
                                    it<span class="token punctuation">.</span><span class="token function">remove</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                                <span class="token punctuation">&#125;</span>

                                <span class="token keyword">break</span><span class="token punctuation">;</span>
                            <span class="token punctuation">&#125;</span>
                        <span class="token punctuation">&#125;</span>
                    <span class="token punctuation">&#125;</span>

                    <span class="token keyword">if</span> <span class="token punctuation">(</span>removeBrokerName<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        <span class="token class-name">Iterator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Entry</span><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">List</span><span class="token punctuation">&lt;</span><span class="token class-name">QueueData</span><span class="token punctuation">></span><span class="token punctuation">></span><span class="token punctuation">></span></span> itTopicQueueTable <span class="token operator">=</span>
                            <span class="token keyword">this</span><span class="token punctuation">.</span>topicQueueTable<span class="token punctuation">.</span><span class="token function">entrySet</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">iterator</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token keyword">while</span> <span class="token punctuation">(</span>itTopicQueueTable<span class="token punctuation">.</span><span class="token function">hasNext</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                            <span class="token class-name">Entry</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">List</span><span class="token punctuation">&lt;</span><span class="token class-name">QueueData</span><span class="token punctuation">></span><span class="token punctuation">></span></span> entry <span class="token operator">=</span> itTopicQueueTable<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token class-name">String</span> topic <span class="token operator">=</span> entry<span class="token punctuation">.</span><span class="token function">getKey</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">QueueData</span><span class="token punctuation">></span></span> queueDataList <span class="token operator">=</span> entry<span class="token punctuation">.</span><span class="token function">getValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

                            <span class="token class-name">Iterator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">QueueData</span><span class="token punctuation">></span></span> itQueueData <span class="token operator">=</span> queueDataList<span class="token punctuation">.</span><span class="token function">iterator</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token keyword">while</span> <span class="token punctuation">(</span>itQueueData<span class="token punctuation">.</span><span class="token function">hasNext</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                <span class="token class-name">QueueData</span> queueData <span class="token operator">=</span> itQueueData<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                                <span class="token keyword">if</span> <span class="token punctuation">(</span>queueData<span class="token punctuation">.</span><span class="token function">getBrokerName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>brokerNameFound<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                    itQueueData<span class="token punctuation">.</span><span class="token function">remove</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                                    log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"remove topic[&#123;&#125; &#123;&#125;], from topicQueueTable, because channel destroyed"</span><span class="token punctuation">,</span>
                                        topic<span class="token punctuation">,</span> queueData<span class="token punctuation">)</span><span class="token punctuation">;</span>
                                <span class="token punctuation">&#125;</span>
                            <span class="token punctuation">&#125;</span>

                            <span class="token keyword">if</span> <span class="token punctuation">(</span>queueDataList<span class="token punctuation">.</span><span class="token function">isEmpty</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                itTopicQueueTable<span class="token punctuation">.</span><span class="token function">remove</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                                log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"remove topic[&#123;&#125;] all queue, from topicQueueTable, because channel destroyed"</span><span class="token punctuation">,</span>
                                    topic<span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token punctuation">&#125;</span>
                        <span class="token punctuation">&#125;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">finally</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">this</span><span class="token punctuation">.</span>lock<span class="token punctuation">.</span><span class="token function">writeLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"onChannelDestroy Exception"</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>第二个是每10分钟打印一次NameServer的配置参数。即KVConfigManager.configTable变量的内容。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">this</span><span class="token punctuation">.</span>scheduledExecutorService<span class="token punctuation">.</span><span class="token function">scheduleAtFixedRate</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Runnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>

            <span class="token annotation punctuation">@Override</span>
            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token class-name">NamesrvController</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>kvConfigManager<span class="token punctuation">.</span><span class="token function">printAllPeriodically</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">,</span> <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>MINUTES<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>然后这个初始化就差不多完成了，后面只需要把remotingServer start一下就好了</p>
<h3 id="处理请求"><a href="#处理请求" class="headerlink" title="处理请求"></a>处理请求</h3><p>直接上代码，其实主体是swtich case去判断</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token class-name">RemotingCommand</span> <span class="token function">processRequest</span><span class="token punctuation">(</span><span class="token class-name">ChannelHandlerContext</span> ctx<span class="token punctuation">,</span>
        <span class="token class-name">RemotingCommand</span> request<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">RemotingCommandException</span> <span class="token punctuation">&#123;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span>ctx <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            log<span class="token punctuation">.</span><span class="token function">debug</span><span class="token punctuation">(</span><span class="token string">"receive request, &#123;&#125; &#123;&#125; &#123;&#125;"</span><span class="token punctuation">,</span>
                request<span class="token punctuation">.</span><span class="token function">getCode</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
                <span class="token class-name">RemotingHelper</span><span class="token punctuation">.</span><span class="token function">parseChannelRemoteAddr</span><span class="token punctuation">(</span>ctx<span class="token punctuation">.</span><span class="token function">channel</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
                request<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>


        <span class="token keyword">switch</span> <span class="token punctuation">(</span>request<span class="token punctuation">.</span><span class="token function">getCode</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">case</span> <span class="token class-name">RequestCode</span><span class="token punctuation">.</span>PUT_KV_CONFIG<span class="token operator">:</span>
                <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">putKVConfig</span><span class="token punctuation">(</span>ctx<span class="token punctuation">,</span> request<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">case</span> <span class="token class-name">RequestCode</span><span class="token punctuation">.</span>GET_KV_CONFIG<span class="token operator">:</span>
                <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getKVConfig</span><span class="token punctuation">(</span>ctx<span class="token punctuation">,</span> request<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">case</span> <span class="token class-name">RequestCode</span><span class="token punctuation">.</span>DELETE_KV_CONFIG<span class="token operator">:</span>
                <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">deleteKVConfig</span><span class="token punctuation">(</span>ctx<span class="token punctuation">,</span> request<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">case</span> <span class="token class-name">RequestCode</span><span class="token punctuation">.</span>QUERY_DATA_VERSION<span class="token operator">:</span>
                <span class="token keyword">return</span> <span class="token function">queryBrokerTopicConfig</span><span class="token punctuation">(</span>ctx<span class="token punctuation">,</span> request<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">case</span> <span class="token class-name">RequestCode</span><span class="token punctuation">.</span>REGISTER_BROKER<span class="token operator">:</span>
                <span class="token class-name">Version</span> brokerVersion <span class="token operator">=</span> <span class="token class-name">MQVersion</span><span class="token punctuation">.</span><span class="token function">value2Version</span><span class="token punctuation">(</span>request<span class="token punctuation">.</span><span class="token function">getVersion</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>brokerVersion<span class="token punctuation">.</span><span class="token function">ordinal</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">>=</span> <span class="token class-name">MQVersion<span class="token punctuation">.</span>Version</span><span class="token punctuation">.</span>V3_0_11<span class="token punctuation">.</span><span class="token function">ordinal</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">registerBrokerWithFilterServer</span><span class="token punctuation">(</span>ctx<span class="token punctuation">,</span> request<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">registerBroker</span><span class="token punctuation">(</span>ctx<span class="token punctuation">,</span> request<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token keyword">case</span> <span class="token class-name">RequestCode</span><span class="token punctuation">.</span>UNREGISTER_BROKER<span class="token operator">:</span>
                <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">unregisterBroker</span><span class="token punctuation">(</span>ctx<span class="token punctuation">,</span> request<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">case</span> <span class="token class-name">RequestCode</span><span class="token punctuation">.</span>GET_ROUTEINTO_BY_TOPIC<span class="token operator">:</span>
                <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getRouteInfoByTopic</span><span class="token punctuation">(</span>ctx<span class="token punctuation">,</span> request<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">case</span> <span class="token class-name">RequestCode</span><span class="token punctuation">.</span>GET_BROKER_CLUSTER_INFO<span class="token operator">:</span>
                <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getBrokerClusterInfo</span><span class="token punctuation">(</span>ctx<span class="token punctuation">,</span> request<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">case</span> <span class="token class-name">RequestCode</span><span class="token punctuation">.</span>WIPE_WRITE_PERM_OF_BROKER<span class="token operator">:</span>
                <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">wipeWritePermOfBroker</span><span class="token punctuation">(</span>ctx<span class="token punctuation">,</span> request<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">case</span> <span class="token class-name">RequestCode</span><span class="token punctuation">.</span>GET_ALL_TOPIC_LIST_FROM_NAMESERVER<span class="token operator">:</span>
                <span class="token keyword">return</span> <span class="token function">getAllTopicListFromNameserver</span><span class="token punctuation">(</span>ctx<span class="token punctuation">,</span> request<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">case</span> <span class="token class-name">RequestCode</span><span class="token punctuation">.</span>DELETE_TOPIC_IN_NAMESRV<span class="token operator">:</span>
                <span class="token keyword">return</span> <span class="token function">deleteTopicInNamesrv</span><span class="token punctuation">(</span>ctx<span class="token punctuation">,</span> request<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">case</span> <span class="token class-name">RequestCode</span><span class="token punctuation">.</span>GET_KVLIST_BY_NAMESPACE<span class="token operator">:</span>
                <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getKVListByNamespace</span><span class="token punctuation">(</span>ctx<span class="token punctuation">,</span> request<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">case</span> <span class="token class-name">RequestCode</span><span class="token punctuation">.</span>GET_TOPICS_BY_CLUSTER<span class="token operator">:</span>
                <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getTopicsByCluster</span><span class="token punctuation">(</span>ctx<span class="token punctuation">,</span> request<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">case</span> <span class="token class-name">RequestCode</span><span class="token punctuation">.</span>GET_SYSTEM_TOPIC_LIST_FROM_NS<span class="token operator">:</span>
                <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getSystemTopicListFromNs</span><span class="token punctuation">(</span>ctx<span class="token punctuation">,</span> request<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">case</span> <span class="token class-name">RequestCode</span><span class="token punctuation">.</span>GET_UNIT_TOPIC_LIST<span class="token operator">:</span>
                <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getUnitTopicList</span><span class="token punctuation">(</span>ctx<span class="token punctuation">,</span> request<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">case</span> <span class="token class-name">RequestCode</span><span class="token punctuation">.</span>GET_HAS_UNIT_SUB_TOPIC_LIST<span class="token operator">:</span>
                <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getHasUnitSubTopicList</span><span class="token punctuation">(</span>ctx<span class="token punctuation">,</span> request<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">case</span> <span class="token class-name">RequestCode</span><span class="token punctuation">.</span>GET_HAS_UNIT_SUB_UNUNIT_TOPIC_LIST<span class="token operator">:</span>
                <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getHasUnitSubUnUnitTopicList</span><span class="token punctuation">(</span>ctx<span class="token punctuation">,</span> request<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">case</span> <span class="token class-name">RequestCode</span><span class="token punctuation">.</span>UPDATE_NAMESRV_CONFIG<span class="token operator">:</span>
                <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">updateConfig</span><span class="token punctuation">(</span>ctx<span class="token punctuation">,</span> request<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">case</span> <span class="token class-name">RequestCode</span><span class="token punctuation">.</span>GET_NAMESRV_CONFIG<span class="token operator">:</span>
                <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getConfig</span><span class="token punctuation">(</span>ctx<span class="token punctuation">,</span> request<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">default</span><span class="token operator">:</span>
                <span class="token keyword">break</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">return</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>以broker注册为例，</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">case</span> <span class="token class-name">RequestCode</span><span class="token punctuation">.</span>REGISTER_BROKER<span class="token operator">:</span>
                <span class="token class-name">Version</span> brokerVersion <span class="token operator">=</span> <span class="token class-name">MQVersion</span><span class="token punctuation">.</span><span class="token function">value2Version</span><span class="token punctuation">(</span>request<span class="token punctuation">.</span><span class="token function">getVersion</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>brokerVersion<span class="token punctuation">.</span><span class="token function">ordinal</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">>=</span> <span class="token class-name">MQVersion<span class="token punctuation">.</span>Version</span><span class="token punctuation">.</span>V3_0_11<span class="token punctuation">.</span><span class="token function">ordinal</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">registerBrokerWithFilterServer</span><span class="token punctuation">(</span>ctx<span class="token punctuation">,</span> request<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">registerBroker</span><span class="token punctuation">(</span>ctx<span class="token punctuation">,</span> request<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>做了个简单的版本管理，我们看下前面一个的代码</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">RemotingCommand</span> <span class="token function">registerBrokerWithFilterServer</span><span class="token punctuation">(</span><span class="token class-name">ChannelHandlerContext</span> ctx<span class="token punctuation">,</span> <span class="token class-name">RemotingCommand</span> request<span class="token punctuation">)</span>
    <span class="token keyword">throws</span> <span class="token class-name">RemotingCommandException</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">final</span> <span class="token class-name">RemotingCommand</span> response <span class="token operator">=</span> <span class="token class-name">RemotingCommand</span><span class="token punctuation">.</span><span class="token function">createResponseCommand</span><span class="token punctuation">(</span><span class="token class-name">RegisterBrokerResponseHeader</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">final</span> <span class="token class-name">RegisterBrokerResponseHeader</span> responseHeader <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">RegisterBrokerResponseHeader</span><span class="token punctuation">)</span> response<span class="token punctuation">.</span><span class="token function">readCustomHeader</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">final</span> <span class="token class-name">RegisterBrokerRequestHeader</span> requestHeader <span class="token operator">=</span>
        <span class="token punctuation">(</span><span class="token class-name">RegisterBrokerRequestHeader</span><span class="token punctuation">)</span> request<span class="token punctuation">.</span><span class="token function">decodeCommandCustomHeader</span><span class="token punctuation">(</span><span class="token class-name">RegisterBrokerRequestHeader</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token function">checksum</span><span class="token punctuation">(</span>ctx<span class="token punctuation">,</span> request<span class="token punctuation">,</span> requestHeader<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        response<span class="token punctuation">.</span><span class="token function">setCode</span><span class="token punctuation">(</span><span class="token class-name">ResponseCode</span><span class="token punctuation">.</span>SYSTEM_ERROR<span class="token punctuation">)</span><span class="token punctuation">;</span>
        response<span class="token punctuation">.</span><span class="token function">setRemark</span><span class="token punctuation">(</span><span class="token string">"crc32 not match"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> response<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token class-name">RegisterBrokerBody</span> registerBrokerBody <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">RegisterBrokerBody</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">if</span> <span class="token punctuation">(</span>request<span class="token punctuation">.</span><span class="token function">getBody</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
            registerBrokerBody <span class="token operator">=</span> <span class="token class-name">RegisterBrokerBody</span><span class="token punctuation">.</span><span class="token function">decode</span><span class="token punctuation">(</span>request<span class="token punctuation">.</span><span class="token function">getBody</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> requestHeader<span class="token punctuation">.</span><span class="token function">isCompressed</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">RemotingCommandException</span><span class="token punctuation">(</span><span class="token string">"Failed to decode RegisterBrokerBody"</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
        registerBrokerBody<span class="token punctuation">.</span><span class="token function">getTopicConfigSerializeWrapper</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getDataVersion</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">setCounter</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">AtomicLong</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        registerBrokerBody<span class="token punctuation">.</span><span class="token function">getTopicConfigSerializeWrapper</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getDataVersion</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">setTimestamp</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token class-name">RegisterBrokerResult</span> result <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>namesrvController<span class="token punctuation">.</span><span class="token function">getRouteInfoManager</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">registerBroker</span><span class="token punctuation">(</span>
        requestHeader<span class="token punctuation">.</span><span class="token function">getClusterName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
        requestHeader<span class="token punctuation">.</span><span class="token function">getBrokerAddr</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
        requestHeader<span class="token punctuation">.</span><span class="token function">getBrokerName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
        requestHeader<span class="token punctuation">.</span><span class="token function">getBrokerId</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
        requestHeader<span class="token punctuation">.</span><span class="token function">getHaServerAddr</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
        registerBrokerBody<span class="token punctuation">.</span><span class="token function">getTopicConfigSerializeWrapper</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
        registerBrokerBody<span class="token punctuation">.</span><span class="token function">getFilterServerList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
        ctx<span class="token punctuation">.</span><span class="token function">channel</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    responseHeader<span class="token punctuation">.</span><span class="token function">setHaServerAddr</span><span class="token punctuation">(</span>result<span class="token punctuation">.</span><span class="token function">getHaServerAddr</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    responseHeader<span class="token punctuation">.</span><span class="token function">setMasterAddr</span><span class="token punctuation">(</span>result<span class="token punctuation">.</span><span class="token function">getMasterAddr</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">byte</span><span class="token punctuation">[</span><span class="token punctuation">]</span> jsonValue <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>namesrvController<span class="token punctuation">.</span><span class="token function">getKvConfigManager</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getKVListByNamespace</span><span class="token punctuation">(</span><span class="token class-name">NamesrvUtil</span><span class="token punctuation">.</span>NAMESPACE_ORDER_TOPIC_CONFIG<span class="token punctuation">)</span><span class="token punctuation">;</span>
    response<span class="token punctuation">.</span><span class="token function">setBody</span><span class="token punctuation">(</span>jsonValue<span class="token punctuation">)</span><span class="token punctuation">;</span>

    response<span class="token punctuation">.</span><span class="token function">setCode</span><span class="token punctuation">(</span><span class="token class-name">ResponseCode</span><span class="token punctuation">.</span>SUCCESS<span class="token punctuation">)</span><span class="token punctuation">;</span>
    response<span class="token punctuation">.</span><span class="token function">setRemark</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> response<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>可以看到主要的逻辑还是在<code>org.apache.rocketmq.namesrv.routeinfo.RouteInfoManager#registerBroker</code>这个方法里</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">RegisterBrokerResult</span> <span class="token function">registerBroker</span><span class="token punctuation">(</span>
        <span class="token keyword">final</span> <span class="token class-name">String</span> clusterName<span class="token punctuation">,</span>
        <span class="token keyword">final</span> <span class="token class-name">String</span> brokerAddr<span class="token punctuation">,</span>
        <span class="token keyword">final</span> <span class="token class-name">String</span> brokerName<span class="token punctuation">,</span>
        <span class="token keyword">final</span> <span class="token keyword">long</span> brokerId<span class="token punctuation">,</span>
        <span class="token keyword">final</span> <span class="token class-name">String</span> haServerAddr<span class="token punctuation">,</span>
        <span class="token keyword">final</span> <span class="token class-name">TopicConfigSerializeWrapper</span> topicConfigWrapper<span class="token punctuation">,</span>
        <span class="token keyword">final</span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">></span></span> filterServerList<span class="token punctuation">,</span>
        <span class="token keyword">final</span> <span class="token class-name">Channel</span> channel<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">RegisterBrokerResult</span> result <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">RegisterBrokerResult</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>lock<span class="token punctuation">.</span><span class="token function">writeLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">lockInterruptibly</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

              <span class="token comment">// 更新这个clusterAddrTable</span>
                <span class="token class-name">Set</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">></span></span> brokerNames <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>clusterAddrTable<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span>clusterName<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">null</span> <span class="token operator">==</span> brokerNames<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    brokerNames <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">HashSet</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">this</span><span class="token punctuation">.</span>clusterAddrTable<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span>clusterName<span class="token punctuation">,</span> brokerNames<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
                brokerNames<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>brokerName<span class="token punctuation">)</span><span class="token punctuation">;</span>

                <span class="token keyword">boolean</span> registerFirst <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>

              <span class="token comment">// 更新brokerAddrTable</span>
                <span class="token class-name">BrokerData</span> brokerData <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>brokerAddrTable<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span>brokerName<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">null</span> <span class="token operator">==</span> brokerData<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    registerFirst <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
                    brokerData <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">BrokerData</span><span class="token punctuation">(</span>clusterName<span class="token punctuation">,</span> brokerName<span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">HashMap</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Long</span><span class="token punctuation">,</span> <span class="token class-name">String</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">this</span><span class="token punctuation">.</span>brokerAddrTable<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span>brokerName<span class="token punctuation">,</span> brokerData<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
                <span class="token class-name">Map</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Long</span><span class="token punctuation">,</span> <span class="token class-name">String</span><span class="token punctuation">></span></span> brokerAddrsMap <span class="token operator">=</span> brokerData<span class="token punctuation">.</span><span class="token function">getBrokerAddrs</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token comment">//Switch slave to master: first remove &lt;1, IP:PORT> in namesrv, then add &lt;0, IP:PORT></span>
                <span class="token comment">//The same IP:PORT must only have one record in brokerAddrTable</span>
                <span class="token class-name">Iterator</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Entry</span><span class="token punctuation">&lt;</span><span class="token class-name">Long</span><span class="token punctuation">,</span> <span class="token class-name">String</span><span class="token punctuation">></span><span class="token punctuation">></span></span> it <span class="token operator">=</span> brokerAddrsMap<span class="token punctuation">.</span><span class="token function">entrySet</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">iterator</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">while</span> <span class="token punctuation">(</span>it<span class="token punctuation">.</span><span class="token function">hasNext</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token class-name">Entry</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Long</span><span class="token punctuation">,</span> <span class="token class-name">String</span><span class="token punctuation">></span></span> item <span class="token operator">=</span> it<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">null</span> <span class="token operator">!=</span> brokerAddr <span class="token operator">&amp;&amp;</span> brokerAddr<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>item<span class="token punctuation">.</span><span class="token function">getValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> brokerId <span class="token operator">!=</span> item<span class="token punctuation">.</span><span class="token function">getKey</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        it<span class="token punctuation">.</span><span class="token function">remove</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span>

                <span class="token class-name">String</span> oldAddr <span class="token operator">=</span> brokerData<span class="token punctuation">.</span><span class="token function">getBrokerAddrs</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span>brokerId<span class="token punctuation">,</span> brokerAddr<span class="token punctuation">)</span><span class="token punctuation">;</span>
                registerFirst <span class="token operator">=</span> registerFirst <span class="token operator">||</span> <span class="token punctuation">(</span><span class="token keyword">null</span> <span class="token operator">==</span> oldAddr<span class="token punctuation">)</span><span class="token punctuation">;</span>

              <span class="token comment">// 更新了org.apache.rocketmq.namesrv.routeinfo.RouteInfoManager#topicQueueTable中的数据</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">null</span> <span class="token operator">!=</span> topicConfigWrapper
                    <span class="token operator">&amp;&amp;</span> <span class="token class-name">MixAll</span><span class="token punctuation">.</span>MASTER_ID <span class="token operator">==</span> brokerId<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">isBrokerTopicConfigChanged</span><span class="token punctuation">(</span>brokerAddr<span class="token punctuation">,</span> topicConfigWrapper<span class="token punctuation">.</span><span class="token function">getDataVersion</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
                        <span class="token operator">||</span> registerFirst<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        <span class="token class-name">ConcurrentMap</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">TopicConfig</span><span class="token punctuation">></span></span> tcTable <span class="token operator">=</span>
                            topicConfigWrapper<span class="token punctuation">.</span><span class="token function">getTopicConfigTable</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token keyword">if</span> <span class="token punctuation">(</span>tcTable <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                            <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">Map<span class="token punctuation">.</span>Entry</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">TopicConfig</span><span class="token punctuation">></span></span> entry <span class="token operator">:</span> tcTable<span class="token punctuation">.</span><span class="token function">entrySet</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">createAndUpdateQueueData</span><span class="token punctuation">(</span>brokerName<span class="token punctuation">,</span> entry<span class="token punctuation">.</span><span class="token function">getValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token punctuation">&#125;</span>
                        <span class="token punctuation">&#125;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span>

              <span class="token comment">// 更新活跃broker信息</span>
                <span class="token class-name">BrokerLiveInfo</span> prevBrokerLiveInfo <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>brokerLiveTable<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span>brokerAddr<span class="token punctuation">,</span>
                    <span class="token keyword">new</span> <span class="token class-name">BrokerLiveInfo</span><span class="token punctuation">(</span>
                        <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">currentTimeMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
                        topicConfigWrapper<span class="token punctuation">.</span><span class="token function">getDataVersion</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
                        channel<span class="token punctuation">,</span>
                        haServerAddr<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">null</span> <span class="token operator">==</span> prevBrokerLiveInfo<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"new broker registered, &#123;&#125; HAServer: &#123;&#125;"</span><span class="token punctuation">,</span> brokerAddr<span class="token punctuation">,</span> haServerAddr<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>

              <span class="token comment">// 处理filter</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>filterServerList <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">if</span> <span class="token punctuation">(</span>filterServerList<span class="token punctuation">.</span><span class="token function">isEmpty</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        <span class="token keyword">this</span><span class="token punctuation">.</span>filterServerTable<span class="token punctuation">.</span><span class="token function">remove</span><span class="token punctuation">(</span>brokerAddr<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                        <span class="token keyword">this</span><span class="token punctuation">.</span>filterServerTable<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span>brokerAddr<span class="token punctuation">,</span> filterServerList<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span>

              <span class="token comment">// 当当前broker非master时返回master信息</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">MixAll</span><span class="token punctuation">.</span>MASTER_ID <span class="token operator">!=</span> brokerId<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token class-name">String</span> masterAddr <span class="token operator">=</span> brokerData<span class="token punctuation">.</span><span class="token function">getBrokerAddrs</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token class-name">MixAll</span><span class="token punctuation">.</span>MASTER_ID<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">if</span> <span class="token punctuation">(</span>masterAddr <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        <span class="token class-name">BrokerLiveInfo</span> brokerLiveInfo <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>brokerLiveTable<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span>masterAddr<span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token keyword">if</span> <span class="token punctuation">(</span>brokerLiveInfo <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                            result<span class="token punctuation">.</span><span class="token function">setHaServerAddr</span><span class="token punctuation">(</span>brokerLiveInfo<span class="token punctuation">.</span><span class="token function">getHaServerAddr</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                            result<span class="token punctuation">.</span><span class="token function">setMasterAddr</span><span class="token punctuation">(</span>masterAddr<span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token punctuation">&#125;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">finally</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>lock<span class="token punctuation">.</span><span class="token function">writeLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"registerBroker Exception"</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">return</span> result<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>这个是注册 broker 的逻辑，再看下根据 topic 获取 broker 信息和 topic 信息，<code>org.apache.rocketmq.namesrv.processor.DefaultRequestProcessor#getRouteInfoByTopic</code> 主要是这个方法的逻辑</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">RemotingCommand</span> <span class="token function">getRouteInfoByTopic</span><span class="token punctuation">(</span><span class="token class-name">ChannelHandlerContext</span> ctx<span class="token punctuation">,</span>
        <span class="token class-name">RemotingCommand</span> request<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">RemotingCommandException</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">final</span> <span class="token class-name">RemotingCommand</span> response <span class="token operator">=</span> <span class="token class-name">RemotingCommand</span><span class="token punctuation">.</span><span class="token function">createResponseCommand</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">final</span> <span class="token class-name">GetRouteInfoRequestHeader</span> requestHeader <span class="token operator">=</span>
            <span class="token punctuation">(</span><span class="token class-name">GetRouteInfoRequestHeader</span><span class="token punctuation">)</span> request<span class="token punctuation">.</span><span class="token function">decodeCommandCustomHeader</span><span class="token punctuation">(</span><span class="token class-name">GetRouteInfoRequestHeader</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token class-name">TopicRouteData</span> topicRouteData <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>namesrvController<span class="token punctuation">.</span><span class="token function">getRouteInfoManager</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">pickupTopicRouteData</span><span class="token punctuation">(</span>requestHeader<span class="token punctuation">.</span><span class="token function">getTopic</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span>topicRouteData <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>namesrvController<span class="token punctuation">.</span><span class="token function">getNamesrvConfig</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">isOrderMessageEnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token class-name">String</span> orderTopicConf <span class="token operator">=</span>
                    <span class="token keyword">this</span><span class="token punctuation">.</span>namesrvController<span class="token punctuation">.</span><span class="token function">getKvConfigManager</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getKVConfig</span><span class="token punctuation">(</span><span class="token class-name">NamesrvUtil</span><span class="token punctuation">.</span>NAMESPACE_ORDER_TOPIC_CONFIG<span class="token punctuation">,</span>
                        requestHeader<span class="token punctuation">.</span><span class="token function">getTopic</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                topicRouteData<span class="token punctuation">.</span><span class="token function">setOrderTopicConf</span><span class="token punctuation">(</span>orderTopicConf<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>

            <span class="token keyword">byte</span><span class="token punctuation">[</span><span class="token punctuation">]</span> content <span class="token operator">=</span> topicRouteData<span class="token punctuation">.</span><span class="token function">encode</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            response<span class="token punctuation">.</span><span class="token function">setBody</span><span class="token punctuation">(</span>content<span class="token punctuation">)</span><span class="token punctuation">;</span>
            response<span class="token punctuation">.</span><span class="token function">setCode</span><span class="token punctuation">(</span><span class="token class-name">ResponseCode</span><span class="token punctuation">.</span>SUCCESS<span class="token punctuation">)</span><span class="token punctuation">;</span>
            response<span class="token punctuation">.</span><span class="token function">setRemark</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">return</span> response<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        response<span class="token punctuation">.</span><span class="token function">setCode</span><span class="token punctuation">(</span><span class="token class-name">ResponseCode</span><span class="token punctuation">.</span>TOPIC_NOT_EXIST<span class="token punctuation">)</span><span class="token punctuation">;</span>
        response<span class="token punctuation">.</span><span class="token function">setRemark</span><span class="token punctuation">(</span><span class="token string">"No topic route info in name server for the topic: "</span> <span class="token operator">+</span> requestHeader<span class="token punctuation">.</span><span class="token function">getTopic</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
            <span class="token operator">+</span> <span class="token class-name">FAQUrl</span><span class="token punctuation">.</span><span class="token function">suggestTodo</span><span class="token punctuation">(</span><span class="token class-name">FAQUrl</span><span class="token punctuation">.</span>APPLY_TOPIC_URL<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> response<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>首先调用<code>org.apache.rocketmq.namesrv.routeinfo.RouteInfoManager#pickupTopicRouteData</code>从<code>org.apache.rocketmq.namesrv.routeinfo.RouteInfoManager#topicQueueTable</code>获取到<code>org.apache.rocketmq.common.protocol.route.QueueData</code>这里面存了 brokerName，再通过<code>org.apache.rocketmq.namesrv.routeinfo.RouteInfoManager#brokerAddrTable</code>里获取到 broker 的地址信息等，然后再获取 orderMessage 的配置。</p>
<p>简要分析了下 RocketMQ 的 NameServer 的代码，比较粗粒度。</p>
]]></content>
      <categories>
        <category>MQ</category>
        <category>RocketMQ</category>
        <category>消息队列</category>
        <category>RocketMQ</category>
        <category>中间件</category>
        <category>RocketMQ</category>
      </categories>
      <tags>
        <tag>MQ</tag>
        <tag>消息队列</tag>
        <tag>RocketMQ</tag>
        <tag>削峰填谷</tag>
        <tag>中间件</tag>
        <tag>NameServer</tag>
        <tag>源码解析</tag>
      </tags>
  </entry>
  <entry>
    <title>聊一下 RocketMQ 的消息存储二</title>
    <url>/2021/09/12/%E8%81%8A%E4%B8%80%E4%B8%8B-RocketMQ-%E7%9A%84%E6%B6%88%E6%81%AF%E5%AD%98%E5%82%A8%E4%BA%8C/</url>
    <content><![CDATA[<h3 id="CommitLog-结构"><a href="#CommitLog-结构" class="headerlink" title="CommitLog 结构"></a>CommitLog 结构</h3><p>CommitLog 是 rocketmq 的服务端，也就是 broker 存储消息的的文件，跟 kafka 一样，也是顺序写入，当然消息是变长的，生成的规则是每个文件的默认1G =1024 * 1024 * 1024，commitlog的文件名fileName，名字长度为20位，左边补零，剩余为起始偏移量；比如00000000000000000000代表了第一个文件，起始偏移量为0，文件大小为1G=1 073 741 824Byte；当这个文件满了，第二个文件名字为00000000001073741824，起始偏移量为1073741824, 消息存储的时候会顺序写入文件，当文件满了则写入下一个文件，代码中的定义</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">// CommitLog file size,default is 1G</span>
<span class="token keyword">private</span> <span class="token keyword">int</span> mapedFileSizeCommitLog <span class="token operator">=</span> <span class="token number">1024</span> <span class="token operator">*</span> <span class="token number">1024</span> <span class="token operator">*</span> <span class="token number">1024</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/kLahwW.png" alt="kLahwW"></p>
<p>本地跑个 demo 验证下，也是这样，这里奇妙有几个比较巧妙的点（个人观点），首先文件就刚好是 1G，并且按照大小偏移量去生成下一个文件，这样获取消息的时候按大小算一下就知道在哪个文件里了，</p>
<p>代码中写入 CommitLog 的逻辑可以从这开始看</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">PutMessageResult</span> <span class="token function">putMessage</span><span class="token punctuation">(</span><span class="token keyword">final</span> <span class="token class-name">MessageExtBrokerInner</span> msg<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token comment">// Set the storage time</span>
        msg<span class="token punctuation">.</span><span class="token function">setStoreTimestamp</span><span class="token punctuation">(</span><span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">currentTimeMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">// Set the message body BODY CRC (consider the most appropriate setting</span>
        <span class="token comment">// on the client)</span>
        msg<span class="token punctuation">.</span><span class="token function">setBodyCRC</span><span class="token punctuation">(</span><span class="token class-name">UtilAll</span><span class="token punctuation">.</span><span class="token function">crc32</span><span class="token punctuation">(</span>msg<span class="token punctuation">.</span><span class="token function">getBody</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">// Back to Results</span>
        <span class="token class-name">AppendMessageResult</span> result <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>

        <span class="token class-name">StoreStatsService</span> storeStatsService <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>defaultMessageStore<span class="token punctuation">.</span><span class="token function">getStoreStatsService</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token class-name">String</span> topic <span class="token operator">=</span> msg<span class="token punctuation">.</span><span class="token function">getTopic</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">int</span> queueId <span class="token operator">=</span> msg<span class="token punctuation">.</span><span class="token function">getQueueId</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">final</span> <span class="token keyword">int</span> tranType <span class="token operator">=</span> <span class="token class-name">MessageSysFlag</span><span class="token punctuation">.</span><span class="token function">getTransactionValue</span><span class="token punctuation">(</span>msg<span class="token punctuation">.</span><span class="token function">getSysFlag</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>tranType <span class="token operator">==</span> <span class="token class-name">MessageSysFlag</span><span class="token punctuation">.</span>TRANSACTION_NOT_TYPE
            <span class="token operator">||</span> tranType <span class="token operator">==</span> <span class="token class-name">MessageSysFlag</span><span class="token punctuation">.</span>TRANSACTION_COMMIT_TYPE<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token comment">// Delay Delivery</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>msg<span class="token punctuation">.</span><span class="token function">getDelayTimeLevel</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">></span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>msg<span class="token punctuation">.</span><span class="token function">getDelayTimeLevel</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">></span> <span class="token keyword">this</span><span class="token punctuation">.</span>defaultMessageStore<span class="token punctuation">.</span><span class="token function">getScheduleMessageService</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getMaxDelayLevel</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    msg<span class="token punctuation">.</span><span class="token function">setDelayTimeLevel</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>defaultMessageStore<span class="token punctuation">.</span><span class="token function">getScheduleMessageService</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getMaxDelayLevel</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>

                topic <span class="token operator">=</span> <span class="token class-name">ScheduleMessageService</span><span class="token punctuation">.</span>SCHEDULE_TOPIC<span class="token punctuation">;</span>
                queueId <span class="token operator">=</span> <span class="token class-name">ScheduleMessageService</span><span class="token punctuation">.</span><span class="token function">delayLevel2QueueId</span><span class="token punctuation">(</span>msg<span class="token punctuation">.</span><span class="token function">getDelayTimeLevel</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

                <span class="token comment">// Backup real topic, queueId</span>
                <span class="token class-name">MessageAccessor</span><span class="token punctuation">.</span><span class="token function">putProperty</span><span class="token punctuation">(</span>msg<span class="token punctuation">,</span> <span class="token class-name">MessageConst</span><span class="token punctuation">.</span>PROPERTY_REAL_TOPIC<span class="token punctuation">,</span> msg<span class="token punctuation">.</span><span class="token function">getTopic</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token class-name">MessageAccessor</span><span class="token punctuation">.</span><span class="token function">putProperty</span><span class="token punctuation">(</span>msg<span class="token punctuation">,</span> <span class="token class-name">MessageConst</span><span class="token punctuation">.</span>PROPERTY_REAL_QUEUE_ID<span class="token punctuation">,</span> <span class="token class-name">String</span><span class="token punctuation">.</span><span class="token function">valueOf</span><span class="token punctuation">(</span>msg<span class="token punctuation">.</span><span class="token function">getQueueId</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                msg<span class="token punctuation">.</span><span class="token function">setPropertiesString</span><span class="token punctuation">(</span><span class="token class-name">MessageDecoder</span><span class="token punctuation">.</span><span class="token function">messageProperties2String</span><span class="token punctuation">(</span>msg<span class="token punctuation">.</span><span class="token function">getProperties</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

                msg<span class="token punctuation">.</span><span class="token function">setTopic</span><span class="token punctuation">(</span>topic<span class="token punctuation">)</span><span class="token punctuation">;</span>
                msg<span class="token punctuation">.</span><span class="token function">setQueueId</span><span class="token punctuation">(</span>queueId<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">long</span> eclipseTimeInLock <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
        <span class="token class-name">MappedFile</span> unlockMappedFile <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
        <span class="token class-name">MappedFile</span> mappedFile <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>mappedFileQueue<span class="token punctuation">.</span><span class="token function">getLastMappedFile</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        putMessageLock<span class="token punctuation">.</span><span class="token function">lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//spin or ReentrantLock ,depending on store config</span>
        <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">long</span> beginLockTimestamp <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>defaultMessageStore<span class="token punctuation">.</span><span class="token function">getSystemClock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>beginTimeInLock <span class="token operator">=</span> beginLockTimestamp<span class="token punctuation">;</span>

            <span class="token comment">// Here settings are stored timestamp, in order to ensure an orderly</span>
            <span class="token comment">// global</span>
            msg<span class="token punctuation">.</span><span class="token function">setStoreTimestamp</span><span class="token punctuation">(</span>beginLockTimestamp<span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">null</span> <span class="token operator">==</span> mappedFile <span class="token operator">||</span> mappedFile<span class="token punctuation">.</span><span class="token function">isFull</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                mappedFile <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>mappedFileQueue<span class="token punctuation">.</span><span class="token function">getLastMappedFile</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// Mark: NewFile may be cause noise</span>
            <span class="token punctuation">&#125;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">null</span> <span class="token operator">==</span> mappedFile<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"create mapped file1 error, topic: "</span> <span class="token operator">+</span> msg<span class="token punctuation">.</span><span class="token function">getTopic</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">" clientAddr: "</span> <span class="token operator">+</span> msg<span class="token punctuation">.</span><span class="token function">getBornHostString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                beginTimeInLock <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
                <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">PutMessageResult</span><span class="token punctuation">(</span><span class="token class-name">PutMessageStatus</span><span class="token punctuation">.</span>CREATE_MAPEDFILE_FAILED<span class="token punctuation">,</span> <span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>

            result <span class="token operator">=</span> mappedFile<span class="token punctuation">.</span><span class="token function">appendMessage</span><span class="token punctuation">(</span>msg<span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>appendMessageCallback<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">switch</span> <span class="token punctuation">(</span>result<span class="token punctuation">.</span><span class="token function">getStatus</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">case</span> PUT_OK<span class="token operator">:</span>
                    <span class="token keyword">break</span><span class="token punctuation">;</span>
                <span class="token keyword">case</span> END_OF_FILE<span class="token operator">:</span>
                    unlockMappedFile <span class="token operator">=</span> mappedFile<span class="token punctuation">;</span>
                    <span class="token comment">// Create a new file, re-write the message</span>
                    mappedFile <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>mappedFileQueue<span class="token punctuation">.</span><span class="token function">getLastMappedFile</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">null</span> <span class="token operator">==</span> mappedFile<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        <span class="token comment">// XXX: warn and notify me</span>
                        log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"create mapped file2 error, topic: "</span> <span class="token operator">+</span> msg<span class="token punctuation">.</span><span class="token function">getTopic</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">" clientAddr: "</span> <span class="token operator">+</span> msg<span class="token punctuation">.</span><span class="token function">getBornHostString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                        beginTimeInLock <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
                        <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">PutMessageResult</span><span class="token punctuation">(</span><span class="token class-name">PutMessageStatus</span><span class="token punctuation">.</span>CREATE_MAPEDFILE_FAILED<span class="token punctuation">,</span> result<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>
                    result <span class="token operator">=</span> mappedFile<span class="token punctuation">.</span><span class="token function">appendMessage</span><span class="token punctuation">(</span>msg<span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>appendMessageCallback<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">break</span><span class="token punctuation">;</span>
                <span class="token keyword">case</span> MESSAGE_SIZE_EXCEEDED<span class="token operator">:</span>
                <span class="token keyword">case</span> PROPERTIES_SIZE_EXCEEDED<span class="token operator">:</span>
                    beginTimeInLock <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
                    <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">PutMessageResult</span><span class="token punctuation">(</span><span class="token class-name">PutMessageStatus</span><span class="token punctuation">.</span>MESSAGE_ILLEGAL<span class="token punctuation">,</span> result<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">case</span> UNKNOWN_ERROR<span class="token operator">:</span>
                    beginTimeInLock <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
                    <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">PutMessageResult</span><span class="token punctuation">(</span><span class="token class-name">PutMessageStatus</span><span class="token punctuation">.</span>UNKNOWN_ERROR<span class="token punctuation">,</span> result<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">default</span><span class="token operator">:</span>
                    beginTimeInLock <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
                    <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">PutMessageResult</span><span class="token punctuation">(</span><span class="token class-name">PutMessageStatus</span><span class="token punctuation">.</span>UNKNOWN_ERROR<span class="token punctuation">,</span> result<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>

            eclipseTimeInLock <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>defaultMessageStore<span class="token punctuation">.</span><span class="token function">getSystemClock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-</span> beginLockTimestamp<span class="token punctuation">;</span>
            beginTimeInLock <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">finally</span> <span class="token punctuation">&#123;</span>
            putMessageLock<span class="token punctuation">.</span><span class="token function">unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span>eclipseTimeInLock <span class="token operator">></span> <span class="token number">500</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token string">"[NOTIFYME]putMessage in lock cost time(ms)=&#123;&#125;, bodyLength=&#123;&#125; AppendMessageResult=&#123;&#125;"</span><span class="token punctuation">,</span> eclipseTimeInLock<span class="token punctuation">,</span> msg<span class="token punctuation">.</span><span class="token function">getBody</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>length<span class="token punctuation">,</span> result<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">null</span> <span class="token operator">!=</span> unlockMappedFile <span class="token operator">&amp;&amp;</span> <span class="token keyword">this</span><span class="token punctuation">.</span>defaultMessageStore<span class="token punctuation">.</span><span class="token function">getMessageStoreConfig</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">isWarmMapedFileEnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>defaultMessageStore<span class="token punctuation">.</span><span class="token function">unlockMappedFile</span><span class="token punctuation">(</span>unlockMappedFile<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token class-name">PutMessageResult</span> putMessageResult <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">PutMessageResult</span><span class="token punctuation">(</span><span class="token class-name">PutMessageStatus</span><span class="token punctuation">.</span>PUT_OK<span class="token punctuation">,</span> result<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment">// Statistics</span>
        storeStatsService<span class="token punctuation">.</span><span class="token function">getSinglePutMessageTopicTimesTotal</span><span class="token punctuation">(</span>msg<span class="token punctuation">.</span><span class="token function">getTopic</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">incrementAndGet</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        storeStatsService<span class="token punctuation">.</span><span class="token function">getSinglePutMessageTopicSizeTotal</span><span class="token punctuation">(</span>topic<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">addAndGet</span><span class="token punctuation">(</span>result<span class="token punctuation">.</span><span class="token function">getWroteBytes</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token function">handleDiskFlush</span><span class="token punctuation">(</span>result<span class="token punctuation">,</span> putMessageResult<span class="token punctuation">,</span> msg<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">handleHA</span><span class="token punctuation">(</span>result<span class="token punctuation">,</span> putMessageResult<span class="token punctuation">,</span> msg<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">return</span> putMessageResult<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>前面也看到在CommitLog 目录下是有大小为 1G 的文件组成，在实现逻辑中，其实是通过 <code>org.apache.rocketmq.store.MappedFileQueue</code> ，内部是存的一个<code>MappedFile</code>的队列，对于写入的场景每次都是通过<code>org.apache.rocketmq.store.MappedFileQueue#getLastMappedFile()</code> 获取最后一个文件，如果还没有创建，或者最后这个文件已经满了，那就调用 <code>org.apache.rocketmq.store.MappedFileQueue#getLastMappedFile(long)</code></p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">MappedFile</span> <span class="token function">getLastMappedFile</span><span class="token punctuation">(</span><span class="token keyword">final</span> <span class="token keyword">long</span> startOffset<span class="token punctuation">,</span> <span class="token keyword">boolean</span> needCreate<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">long</span> createOffset <span class="token operator">=</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">;</span>
  			<span class="token comment">// 调用前面的方法，只是从 mappedFileQueue 获取最后一个</span>
        <span class="token class-name">MappedFile</span> mappedFileLast <span class="token operator">=</span> <span class="token function">getLastMappedFile</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment">// 如果为空，计算下创建的偏移量</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>mappedFileLast <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            createOffset <span class="token operator">=</span> startOffset <span class="token operator">-</span> <span class="token punctuation">(</span>startOffset <span class="token operator">%</span> <span class="token keyword">this</span><span class="token punctuation">.</span>mappedFileSize<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
  
				<span class="token comment">// 如果不为空，但是当前的文件写满了</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>mappedFileLast <span class="token operator">!=</span> <span class="token keyword">null</span> <span class="token operator">&amp;&amp;</span> mappedFileLast<span class="token punctuation">.</span><span class="token function">isFull</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token comment">// 前一个的偏移量加上单个文件的偏移量，也就是 1G</span>
            createOffset <span class="token operator">=</span> mappedFileLast<span class="token punctuation">.</span><span class="token function">getFileFromOffset</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token keyword">this</span><span class="token punctuation">.</span>mappedFileSize<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span>createOffset <span class="token operator">!=</span> <span class="token operator">-</span><span class="token number">1</span> <span class="token operator">&amp;&amp;</span> needCreate<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token comment">// 根据 createOffset 转换成文件名进行创建</span>
            <span class="token class-name">String</span> nextFilePath <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>storePath <span class="token operator">+</span> <span class="token class-name">File</span><span class="token punctuation">.</span>separator <span class="token operator">+</span> <span class="token class-name">UtilAll</span><span class="token punctuation">.</span><span class="token function">offset2FileName</span><span class="token punctuation">(</span>createOffset<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">String</span> nextNextFilePath <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>storePath <span class="token operator">+</span> <span class="token class-name">File</span><span class="token punctuation">.</span>separator
                <span class="token operator">+</span> <span class="token class-name">UtilAll</span><span class="token punctuation">.</span><span class="token function">offset2FileName</span><span class="token punctuation">(</span>createOffset <span class="token operator">+</span> <span class="token keyword">this</span><span class="token punctuation">.</span>mappedFileSize<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">MappedFile</span> mappedFile <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>

          	<span class="token comment">// 这里如果allocateMappedFileService 存在，就提交请求</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>allocateMappedFileService <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                mappedFile <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>allocateMappedFileService<span class="token punctuation">.</span><span class="token function">putRequestAndReturnMappedFile</span><span class="token punctuation">(</span>nextFilePath<span class="token punctuation">,</span>
                    nextNextFilePath<span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>mappedFileSize<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                  <span class="token comment">// 否则就直接创建</span>
                    mappedFile <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">MappedFile</span><span class="token punctuation">(</span>nextFilePath<span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>mappedFileSize<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">IOException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"create mappedFile exception"</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span>

            <span class="token keyword">if</span> <span class="token punctuation">(</span>mappedFile <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>mappedFiles<span class="token punctuation">.</span><span class="token function">isEmpty</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    mappedFile<span class="token punctuation">.</span><span class="token function">setFirstCreateInQueue</span><span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>mappedFiles<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>mappedFile<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>

            <span class="token keyword">return</span> mappedFile<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">return</span> mappedFileLast<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>首先看下直接创建的，</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">MappedFile</span><span class="token punctuation">(</span><span class="token keyword">final</span> <span class="token class-name">String</span> fileName<span class="token punctuation">,</span> <span class="token keyword">final</span> <span class="token keyword">int</span> fileSize<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">IOException</span> <span class="token punctuation">&#123;</span>
        <span class="token function">init</span><span class="token punctuation">(</span>fileName<span class="token punctuation">,</span> fileSize<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">init</span><span class="token punctuation">(</span><span class="token keyword">final</span> <span class="token class-name">String</span> fileName<span class="token punctuation">,</span> <span class="token keyword">final</span> <span class="token keyword">int</span> fileSize<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">IOException</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>fileName <span class="token operator">=</span> fileName<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>fileSize <span class="token operator">=</span> fileSize<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>file <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">File</span><span class="token punctuation">(</span>fileName<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>fileFromOffset <span class="token operator">=</span> <span class="token class-name">Long</span><span class="token punctuation">.</span><span class="token function">parseLong</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>file<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">boolean</span> ok <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>

        <span class="token function">ensureDirOK</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>file<span class="token punctuation">.</span><span class="token function">getParent</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
          <span class="token comment">// 通过 RandomAccessFile 创建 fileChannel</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>fileChannel <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">RandomAccessFile</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>file<span class="token punctuation">,</span> <span class="token string">"rw"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getChannel</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
          <span class="token comment">// 做 mmap 映射</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>mappedByteBuffer <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>fileChannel<span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span><span class="token class-name">MapMode</span><span class="token punctuation">.</span>READ_WRITE<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> fileSize<span class="token punctuation">)</span><span class="token punctuation">;</span>
            TOTAL_MAPPED_VIRTUAL_MEMORY<span class="token punctuation">.</span><span class="token function">addAndGet</span><span class="token punctuation">(</span>fileSize<span class="token punctuation">)</span><span class="token punctuation">;</span>
            TOTAL_MAPPED_FILES<span class="token punctuation">.</span><span class="token function">incrementAndGet</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            ok <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">FileNotFoundException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"create file channel "</span> <span class="token operator">+</span> <span class="token keyword">this</span><span class="token punctuation">.</span>fileName <span class="token operator">+</span> <span class="token string">" Failed. "</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">throw</span> e<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">IOException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"map file "</span> <span class="token operator">+</span> <span class="token keyword">this</span><span class="token punctuation">.</span>fileName <span class="token operator">+</span> <span class="token string">" Failed. "</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">throw</span> e<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">finally</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>ok <span class="token operator">&amp;&amp;</span> <span class="token keyword">this</span><span class="token punctuation">.</span>fileChannel <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>fileChannel<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>如果是提交给<code>AllocateMappedFileService</code>的话就用到了一些异步操作</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">MappedFile</span> <span class="token function">putRequestAndReturnMappedFile</span><span class="token punctuation">(</span><span class="token class-name">String</span> nextFilePath<span class="token punctuation">,</span> <span class="token class-name">String</span> nextNextFilePath<span class="token punctuation">,</span> <span class="token keyword">int</span> fileSize<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">int</span> canSubmitRequests <span class="token operator">=</span> <span class="token number">2</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>messageStore<span class="token punctuation">.</span><span class="token function">getMessageStoreConfig</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">isTransientStorePoolEnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>messageStore<span class="token punctuation">.</span><span class="token function">getMessageStoreConfig</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">isFastFailIfNoBufferInStorePool</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
                <span class="token operator">&amp;&amp;</span> <span class="token class-name">BrokerRole</span><span class="token punctuation">.</span>SLAVE <span class="token operator">!=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>messageStore<span class="token punctuation">.</span><span class="token function">getMessageStoreConfig</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getBrokerRole</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span> <span class="token comment">//if broker is slave, don't fast fail even no buffer in pool</span>
                canSubmitRequests <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>messageStore<span class="token punctuation">.</span><span class="token function">getTransientStorePool</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">remainBufferNumbs</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-</span> <span class="token keyword">this</span><span class="token punctuation">.</span>requestQueue<span class="token punctuation">.</span><span class="token function">size</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
				<span class="token comment">// 将请求放在 requestTable 中</span>
        <span class="token class-name">AllocateRequest</span> nextReq <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">AllocateRequest</span><span class="token punctuation">(</span>nextFilePath<span class="token punctuation">,</span> fileSize<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">boolean</span> nextPutOK <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>requestTable<span class="token punctuation">.</span><span class="token function">putIfAbsent</span><span class="token punctuation">(</span>nextFilePath<span class="token punctuation">,</span> nextReq<span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
        <span class="token comment">// requestTable 使用了 concurrentHashMap，用文件名作为 key，防止并发</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>nextPutOK<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token comment">// 这里判断了是否可以提交到 TransientStorePool，涉及读写分离，后面再细聊</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>canSubmitRequests <span class="token operator">&lt;=</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token string">"[NOTIFYME]TransientStorePool is not enough, so create mapped file error, "</span> <span class="token operator">+</span>
                    <span class="token string">"RequestQueueSize : &#123;&#125;, StorePoolSize: &#123;&#125;"</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>requestQueue<span class="token punctuation">.</span><span class="token function">size</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>messageStore<span class="token punctuation">.</span><span class="token function">getTransientStorePool</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">remainBufferNumbs</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>requestTable<span class="token punctuation">.</span><span class="token function">remove</span><span class="token punctuation">(</span>nextFilePath<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">return</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
          <span class="token comment">// 塞到阻塞队列中</span>
            <span class="token keyword">boolean</span> offerOK <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>requestQueue<span class="token punctuation">.</span><span class="token function">offer</span><span class="token punctuation">(</span>nextReq<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>offerOK<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token string">"never expected here, add a request to preallocate queue failed"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
            canSubmitRequests<span class="token operator">--</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token comment">// 这里的两个提交我猜测是为了多生成一个 CommitLog，</span>
        <span class="token class-name">AllocateRequest</span> nextNextReq <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">AllocateRequest</span><span class="token punctuation">(</span>nextNextFilePath<span class="token punctuation">,</span> fileSize<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">boolean</span> nextNextPutOK <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>requestTable<span class="token punctuation">.</span><span class="token function">putIfAbsent</span><span class="token punctuation">(</span>nextNextFilePath<span class="token punctuation">,</span> nextNextReq<span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>nextNextPutOK<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>canSubmitRequests <span class="token operator">&lt;=</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token string">"[NOTIFYME]TransientStorePool is not enough, so skip preallocate mapped file, "</span> <span class="token operator">+</span>
                    <span class="token string">"RequestQueueSize : &#123;&#125;, StorePoolSize: &#123;&#125;"</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>requestQueue<span class="token punctuation">.</span><span class="token function">size</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>messageStore<span class="token punctuation">.</span><span class="token function">getTransientStorePool</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">remainBufferNumbs</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>requestTable<span class="token punctuation">.</span><span class="token function">remove</span><span class="token punctuation">(</span>nextNextFilePath<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">boolean</span> offerOK <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>requestQueue<span class="token punctuation">.</span><span class="token function">offer</span><span class="token punctuation">(</span>nextNextReq<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>offerOK<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token string">"never expected here, add a request to preallocate queue failed"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span>hasException<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getServiceName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">" service has exception. so return null"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">return</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token class-name">AllocateRequest</span> result <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>requestTable<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span>nextFilePath<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
          <span class="token comment">// 这里就异步等着</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>result <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">boolean</span> waitOK <span class="token operator">=</span> result<span class="token punctuation">.</span><span class="token function">getCountDownLatch</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">await</span><span class="token punctuation">(</span>waitTimeOut<span class="token punctuation">,</span> <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>MILLISECONDS<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>waitOK<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token string">"create mmap timeout "</span> <span class="token operator">+</span> result<span class="token punctuation">.</span><span class="token function">getFilePath</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">" "</span> <span class="token operator">+</span> result<span class="token punctuation">.</span><span class="token function">getFileSize</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">return</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">this</span><span class="token punctuation">.</span>requestTable<span class="token punctuation">.</span><span class="token function">remove</span><span class="token punctuation">(</span>nextFilePath<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">return</span> result<span class="token punctuation">.</span><span class="token function">getMappedFile</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"find preallocate mmap failed, this never happen"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getServiceName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">" service has exception. "</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">return</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>而真正去执行文件操作的就是 <code>AllocateMappedFileService</code>的 run 方法</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getServiceName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">" service started"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">isStopped</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">mmapOperation</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>

        <span class="token punctuation">&#125;</span>
        log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getServiceName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">" service end"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token keyword">private</span> <span class="token keyword">boolean</span> <span class="token function">mmapOperation</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">boolean</span> isSuccess <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
        <span class="token class-name">AllocateRequest</span> req <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
        <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
          <span class="token comment">// 从阻塞队列里获取请求</span>
            req <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>requestQueue<span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">AllocateRequest</span> expectedRequest <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>requestTable<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span>req<span class="token punctuation">.</span><span class="token function">getFilePath</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">null</span> <span class="token operator">==</span> expectedRequest<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token string">"this mmap request expired, maybe cause timeout "</span> <span class="token operator">+</span> req<span class="token punctuation">.</span><span class="token function">getFilePath</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">" "</span>
                    <span class="token operator">+</span> req<span class="token punctuation">.</span><span class="token function">getFileSize</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>expectedRequest <span class="token operator">!=</span> req<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token string">"never expected here,  maybe cause timeout "</span> <span class="token operator">+</span> req<span class="token punctuation">.</span><span class="token function">getFilePath</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">" "</span>
                    <span class="token operator">+</span> req<span class="token punctuation">.</span><span class="token function">getFileSize</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">", req:"</span> <span class="token operator">+</span> req <span class="token operator">+</span> <span class="token string">", expectedRequest:"</span> <span class="token operator">+</span> expectedRequest<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>

            <span class="token keyword">if</span> <span class="token punctuation">(</span>req<span class="token punctuation">.</span><span class="token function">getMappedFile</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">long</span> beginTime <span class="token operator">=</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">currentTimeMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

                <span class="token class-name">MappedFile</span> mappedFile<span class="token punctuation">;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>messageStore<span class="token punctuation">.</span><span class="token function">getMessageStoreConfig</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">isTransientStorePoolEnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                      <span class="token comment">// 通过 transientStorePool 创建</span>
                        mappedFile <span class="token operator">=</span> <span class="token class-name">ServiceLoader</span><span class="token punctuation">.</span><span class="token function">load</span><span class="token punctuation">(</span><span class="token class-name">MappedFile</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">iterator</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                        mappedFile<span class="token punctuation">.</span><span class="token function">init</span><span class="token punctuation">(</span>req<span class="token punctuation">.</span><span class="token function">getFilePath</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> req<span class="token punctuation">.</span><span class="token function">getFileSize</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> messageStore<span class="token punctuation">.</span><span class="token function">getTransientStorePool</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">RuntimeException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token string">"Use default implementation."</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                      <span class="token comment">// 默认创建</span>
                        mappedFile <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">MappedFile</span><span class="token punctuation">(</span>req<span class="token punctuation">.</span><span class="token function">getFilePath</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> req<span class="token punctuation">.</span><span class="token function">getFileSize</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> messageStore<span class="token punctuation">.</span><span class="token function">getTransientStorePool</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                  <span class="token comment">// 默认创建</span>
                    mappedFile <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">MappedFile</span><span class="token punctuation">(</span>req<span class="token punctuation">.</span><span class="token function">getFilePath</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> req<span class="token punctuation">.</span><span class="token function">getFileSize</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>

                <span class="token keyword">long</span> eclipseTime <span class="token operator">=</span> <span class="token class-name">UtilAll</span><span class="token punctuation">.</span><span class="token function">computeEclipseTimeMilliseconds</span><span class="token punctuation">(</span>beginTime<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>eclipseTime <span class="token operator">></span> <span class="token number">10</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">int</span> queueSize <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>requestQueue<span class="token punctuation">.</span><span class="token function">size</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token string">"create mappedFile spent time(ms) "</span> <span class="token operator">+</span> eclipseTime <span class="token operator">+</span> <span class="token string">" queue size "</span> <span class="token operator">+</span> queueSize
                        <span class="token operator">+</span> <span class="token string">" "</span> <span class="token operator">+</span> req<span class="token punctuation">.</span><span class="token function">getFilePath</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">" "</span> <span class="token operator">+</span> req<span class="token punctuation">.</span><span class="token function">getFileSize</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>

                <span class="token comment">// pre write mappedFile</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>mappedFile<span class="token punctuation">.</span><span class="token function">getFileSize</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">>=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>messageStore<span class="token punctuation">.</span><span class="token function">getMessageStoreConfig</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
                    <span class="token punctuation">.</span><span class="token function">getMapedFileSizeCommitLog</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
                    <span class="token operator">&amp;&amp;</span>
                    <span class="token keyword">this</span><span class="token punctuation">.</span>messageStore<span class="token punctuation">.</span><span class="token function">getMessageStoreConfig</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">isWarmMapedFileEnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    mappedFile<span class="token punctuation">.</span><span class="token function">warmMappedFile</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>messageStore<span class="token punctuation">.</span><span class="token function">getMessageStoreConfig</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getFlushDiskType</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
                        <span class="token keyword">this</span><span class="token punctuation">.</span>messageStore<span class="token punctuation">.</span><span class="token function">getMessageStoreConfig</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getFlushLeastPagesWhenWarmMapedFile</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>

                req<span class="token punctuation">.</span><span class="token function">setMappedFile</span><span class="token punctuation">(</span>mappedFile<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>hasException <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
                isSuccess <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getServiceName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">" interrupted, possibly by shutdown."</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>hasException <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
            <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">IOException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getServiceName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">" service has exception. "</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>hasException <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">null</span> <span class="token operator">!=</span> req<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                requestQueue<span class="token punctuation">.</span><span class="token function">offer</span><span class="token punctuation">(</span>req<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                    <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> ignored<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">finally</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>req <span class="token operator">!=</span> <span class="token keyword">null</span> <span class="token operator">&amp;&amp;</span> isSuccess<span class="token punctuation">)</span>
              <span class="token comment">// 通知前面等待的</span>
                req<span class="token punctuation">.</span><span class="token function">getCountDownLatch</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">countDown</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>




]]></content>
      <categories>
        <category>MQ</category>
        <category>RocketMQ</category>
        <category>消息队列</category>
      </categories>
      <tags>
        <tag>MQ</tag>
        <tag>消息队列</tag>
        <tag>RocketMQ</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊 Java 的类加载机制二</title>
    <url>/2021/06/13/%E8%81%8A%E8%81%8A-Java-%E7%9A%84%E7%B1%BB%E5%8A%A0%E8%BD%BD%E6%9C%BA%E5%88%B6%E4%BA%8C/</url>
    <content><![CDATA[<h2 id="类加载器"><a href="#类加载器" class="headerlink" title="类加载器"></a>类加载器</h2><p>类加载机制中说来说去其实也逃不开类加载器这个话题，我们就来说下类加载器这个话题，Java 在 jdk1.2 以后开始有了<br>Java 虚拟机设计团队有意把加载阶段中的“通过一个类的全限定名来获取描述该类的二进制字节流”这个动作放到 Java 虚拟机外部去实现，以便让应用程序自己去决定如何去获取所需的类。实现这个动作的代码被称为“类加载器”(Class Loader).<br>其实在 Java 中类加载器有一个很常用的作用，比如一个类的唯一性，其实是由加载它的类加载器和这个类一起来确定这个类在虚拟机的唯一性，这里也参考下周志明书里的例子</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ClassLoaderTest</span> <span class="token punctuation">&#123;</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">Exception</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">ClassLoader</span> myLoader <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ClassLoader</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token annotation punctuation">@Override</span>
            <span class="token keyword">public</span> <span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span> <span class="token function">loadClass</span><span class="token punctuation">(</span><span class="token class-name">String</span> name<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">ClassNotFoundException</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                    <span class="token class-name">String</span> fileName <span class="token operator">=</span> name<span class="token punctuation">.</span><span class="token function">substring</span><span class="token punctuation">(</span>name<span class="token punctuation">.</span><span class="token function">lastIndexOf</span><span class="token punctuation">(</span><span class="token string">"."</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">".class"</span><span class="token punctuation">;</span>
                    <span class="token class-name">InputStream</span> is <span class="token operator">=</span> <span class="token function">getClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getResourceAsStream</span><span class="token punctuation">(</span>fileName<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">if</span> <span class="token punctuation">(</span>is <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        <span class="token keyword">return</span> <span class="token keyword">super</span><span class="token punctuation">.</span><span class="token function">loadClass</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>
                    <span class="token keyword">byte</span><span class="token punctuation">[</span><span class="token punctuation">]</span> b <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token keyword">byte</span><span class="token punctuation">[</span>is<span class="token punctuation">.</span><span class="token function">available</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
                    is<span class="token punctuation">.</span><span class="token function">read</span><span class="token punctuation">(</span>b<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">return</span> <span class="token function">defineClass</span><span class="token punctuation">(</span>name<span class="token punctuation">,</span> b<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> b<span class="token punctuation">.</span>length<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">IOException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">ClassNotFoundException</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">;</span>
        <span class="token class-name">Object</span> object <span class="token operator">=</span> myLoader<span class="token punctuation">.</span><span class="token function">loadClass</span><span class="token punctuation">(</span><span class="token string">"com.nicksxs.demo.ClassLoaderTest"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">newInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>object<span class="token punctuation">.</span><span class="token function">getClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>object <span class="token keyword">instanceof</span> <span class="token class-name">ClassLoaderTest</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>可以看下结果<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/ADIJqg.png"><br>这里说明了当一个是由虚拟机的应用程序类加载器所加载的和另一个由自己写的自定义类加载器加载的，虽然是同一个类，但是 instanceof 的结果就是 false 的</p>
<h2 id="双亲委派"><a href="#双亲委派" class="headerlink" title="双亲委派"></a>双亲委派</h2><p>自 JDK1.2 以来，Java 一直有些三层类加载器、双亲委派的类加载架构</p>
<h3 id="启动类加载器"><a href="#启动类加载器" class="headerlink" title="启动类加载器"></a>启动类加载器</h3><p>首先是启动类加载器，<code>Bootstrap Class Loader</code>，这个类加载器负责加载放在<JAVA_HOME>\lib目录，或者被-Xbootclasspath参数所指定的路径中存放的，而且是Java 虚拟机能够识别的（按照文件名识别，如 rt.jar、tools.jar，名字不符合的类库即使放在 lib 目录中，也不会被加载）类库加载到虚拟机的内存中，启动类加载器无法被 Java 程序直接引用，用户在编写自定义类加载器时，如果需要把家在请求为派给引导类加载器去处理，那直接使用 null 代替即可，可以看下 java.lang.ClassLoader.getClassLoader()方法的代码片段</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">/**
     * Returns the class loader for the class.  Some implementations may use
     * null to represent the bootstrap class loader. This method will return
     * null in such implementations if this class was loaded by the bootstrap
     * class loader.
     *
     * &lt;p> If a security manager is present, and the caller's class loader is
     * not null and the caller's class loader is not the same as or an ancestor of
     * the class loader for the class whose class loader is requested, then
     * this method calls the security manager's &#123;@code checkPermission&#125;
     * method with a &#123;@code RuntimePermission("getClassLoader")&#125;
     * permission to ensure it's ok to access the class loader for the class.
     *
     * &lt;p>If this object
     * represents a primitive type or void, null is returned.
     *
     * @return  the class loader that loaded the class or interface
     *          represented by this object.
     * @throws SecurityException
     *    if a security manager exists and its
     *    &#123;@code checkPermission&#125; method denies
     *    access to the class loader for the class.
     * @see java.lang.ClassLoader
     * @see SecurityManager#checkPermission
     * @see java.lang.RuntimePermission
     */</span>
    <span class="token annotation punctuation">@CallerSensitive</span>
    <span class="token keyword">public</span> <span class="token class-name">ClassLoader</span> <span class="token function">getClassLoader</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">ClassLoader</span> cl <span class="token operator">=</span> <span class="token function">getClassLoader0</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>cl <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span>
            <span class="token keyword">return</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
        <span class="token class-name">SecurityManager</span> sm <span class="token operator">=</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">getSecurityManager</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>sm <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">ClassLoader</span><span class="token punctuation">.</span><span class="token function">checkClassLoaderPermission</span><span class="token punctuation">(</span>cl<span class="token punctuation">,</span> <span class="token class-name">Reflection</span><span class="token punctuation">.</span><span class="token function">getCallerClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">return</span> cl<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="扩展类加载器"><a href="#扩展类加载器" class="headerlink" title="扩展类加载器"></a>扩展类加载器</h3><p>这个类加载器是在类sun.misc.Launcher.ExtClassLoader中以 Java 代码的形式实现的，它负责在家<JAVA_HOME>\lib\ext 目录中，或者被 java.ext.dirs系统变量中所指定的路径中的所有类库，它其实目的是为了实现 Java 系统类库的扩展机制</p>
<h3 id="应用程序类加载器"><a href="#应用程序类加载器" class="headerlink" title="应用程序类加载器"></a>应用程序类加载器</h3><p>这个类加载器是由sun.misc.Launcher.AppClassLoader实现，通过 java 代码，并且是 ClassLoader 类中的 getSystemClassLoader()方法的返回值，可以看一下代码</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">/**
     * Returns the system class loader for delegation.  This is the default
     * delegation parent for new &lt;tt>ClassLoader&lt;/tt> instances, and is
     * typically the class loader used to start the application.
     *
     * &lt;p> This method is first invoked early in the runtime's startup
     * sequence, at which point it creates the system class loader and sets it
     * as the context class loader of the invoking &lt;tt>Thread&lt;/tt>.
     *
     * &lt;p> The default system class loader is an implementation-dependent
     * instance of this class.
     *
     * &lt;p> If the system property "&lt;tt>java.system.class.loader&lt;/tt>" is defined
     * when this method is first invoked then the value of that property is
     * taken to be the name of a class that will be returned as the system
     * class loader.  The class is loaded using the default system class loader
     * and must define a public constructor that takes a single parameter of
     * type &lt;tt>ClassLoader&lt;/tt> which is used as the delegation parent.  An
     * instance is then created using this constructor with the default system
     * class loader as the parameter.  The resulting class loader is defined
     * to be the system class loader.
     *
     * &lt;p> If a security manager is present, and the invoker's class loader is
     * not &lt;tt>null&lt;/tt> and the invoker's class loader is not the same as or
     * an ancestor of the system class loader, then this method invokes the
     * security manager's &#123;@link
     * SecurityManager#checkPermission(java.security.Permission)
     * &lt;tt>checkPermission&lt;/tt>&#125; method with a &#123;@link
     * RuntimePermission#RuntimePermission(String)
     * &lt;tt>RuntimePermission("getClassLoader")&lt;/tt>&#125; permission to verify
     * access to the system class loader.  If not, a
     * &lt;tt>SecurityException&lt;/tt> will be thrown.  &lt;/p>
     *
     * @return  The system &lt;tt>ClassLoader&lt;/tt> for delegation, or
     *          &lt;tt>null&lt;/tt> if none
     *
     * @throws  SecurityException
     *          If a security manager exists and its &lt;tt>checkPermission&lt;/tt>
     *          method doesn't allow access to the system class loader.
     *
     * @throws  IllegalStateException
     *          If invoked recursively during the construction of the class
     *          loader specified by the "&lt;tt>java.system.class.loader&lt;/tt>"
     *          property.
     *
     * @throws  Error
     *          If the system property "&lt;tt>java.system.class.loader&lt;/tt>"
     *          is defined but the named class could not be loaded, the
     *          provider class does not define the required constructor, or an
     *          exception is thrown by that constructor when it is invoked. The
     *          underlying cause of the error can be retrieved via the
     *          &#123;@link Throwable#getCause()&#125; method.
     *
     * @revised  1.4
     */</span>
    <span class="token annotation punctuation">@CallerSensitive</span>
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token class-name">ClassLoader</span> <span class="token function">getSystemClassLoader</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token function">initSystemClassLoader</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>scl <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token class-name">SecurityManager</span> sm <span class="token operator">=</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">getSecurityManager</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>sm <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token function">checkClassLoaderPermission</span><span class="token punctuation">(</span>scl<span class="token punctuation">,</span> <span class="token class-name">Reflection</span><span class="token punctuation">.</span><span class="token function">getCallerClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">return</span> scl<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">synchronized</span> <span class="token keyword">void</span> <span class="token function">initSystemClassLoader</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>sclSet<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>scl <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span>
                <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">IllegalStateException</span><span class="token punctuation">(</span><span class="token string">"recursive invocation"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token comment">// 主要的第一步是这</span>
            <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>misc<span class="token punctuation">.</span></span>Launcher</span> l <span class="token operator">=</span> <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>misc<span class="token punctuation">.</span></span>Launcher</span><span class="token punctuation">.</span><span class="token function">getLauncher</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>l <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token class-name">Throwable</span> oops <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
                <span class="token comment">// 然后是这</span>
                scl <span class="token operator">=</span> l<span class="token punctuation">.</span><span class="token function">getClassLoader</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                    scl <span class="token operator">=</span> <span class="token class-name">AccessController</span><span class="token punctuation">.</span><span class="token function">doPrivileged</span><span class="token punctuation">(</span>
                        <span class="token keyword">new</span> <span class="token class-name">SystemClassLoaderAction</span><span class="token punctuation">(</span>scl<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">PrivilegedActionException</span> pae<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    oops <span class="token operator">=</span> pae<span class="token punctuation">.</span><span class="token function">getCause</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">if</span> <span class="token punctuation">(</span>oops <span class="token keyword">instanceof</span> <span class="token class-name">InvocationTargetException</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        oops <span class="token operator">=</span> oops<span class="token punctuation">.</span><span class="token function">getCause</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>oops <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">if</span> <span class="token punctuation">(</span>oops <span class="token keyword">instanceof</span> <span class="token class-name">Error</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        <span class="token keyword">throw</span> <span class="token punctuation">(</span><span class="token class-name">Error</span><span class="token punctuation">)</span> oops<span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                        <span class="token comment">// wrap the exception</span>
                        <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">Error</span><span class="token punctuation">(</span>oops<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span>
            sclSet <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>
<span class="token comment">// 接着跟到sun.misc.Launcher#getClassLoader</span>
<span class="token keyword">public</span> <span class="token class-name">ClassLoader</span> <span class="token function">getClassLoader</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span>loader<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token comment">// 然后看到这 sun.misc.Launcher#Launcher</span>
<span class="token keyword">public</span> <span class="token class-name">Launcher</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">Launcher<span class="token punctuation">.</span>ExtClassLoader</span> var1<span class="token punctuation">;</span>
        <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
            var1 <span class="token operator">=</span> <span class="token class-name">Launcher<span class="token punctuation">.</span>ExtClassLoader</span><span class="token punctuation">.</span><span class="token function">getExtClassLoader</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">IOException</span> var10<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">InternalError</span><span class="token punctuation">(</span><span class="token string">"Could not create extension class loader"</span><span class="token punctuation">,</span> var10<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
            <span class="token comment">// 可以看到 就是 AppClassLoader</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>loader <span class="token operator">=</span> <span class="token class-name">Launcher<span class="token punctuation">.</span>AppClassLoader</span><span class="token punctuation">.</span><span class="token function">getAppClassLoader</span><span class="token punctuation">(</span>var1<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">IOException</span> var9<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">InternalError</span><span class="token punctuation">(</span><span class="token string">"Could not create application class loader"</span><span class="token punctuation">,</span> var9<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">setContextClassLoader</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>loader<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">String</span> var2 <span class="token operator">=</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">getProperty</span><span class="token punctuation">(</span><span class="token string">"java.security.manager"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>var2 <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">SecurityManager</span> var3 <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token string">""</span><span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>var2<span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> <span class="token operator">!</span><span class="token string">"default"</span><span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>var2<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                    var3 <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">SecurityManager</span><span class="token punctuation">)</span><span class="token keyword">this</span><span class="token punctuation">.</span>loader<span class="token punctuation">.</span><span class="token function">loadClass</span><span class="token punctuation">(</span>var2<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">newInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">IllegalAccessException</span> var5<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InstantiationException</span> var6<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">ClassNotFoundException</span> var7<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">ClassCastException</span> var8<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                var3 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">SecurityManager</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>

            <span class="token keyword">if</span> <span class="token punctuation">(</span>var3 <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">InternalError</span><span class="token punctuation">(</span><span class="token string">"Could not create SecurityManager: "</span> <span class="token operator">+</span> var2<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>

            <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">setSecurityManager</span><span class="token punctuation">(</span>var3<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>它负责加载用户类路径(ClassPath)上所有的类库，我们可以直接在代码中使用这个类加载器，如果我们的代码中没有自定义的类在加载器，一般情况下这个就是程序中默认的类加载器</p>
<h3 id="双亲委派模型"><a href="#双亲委派模型" class="headerlink" title="双亲委派模型"></a>双亲委派模型</h3><p><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/ztS0pn.png"><br>双亲委派模型的工作过程是：如果一个类加载器收到了类加载的请求，它首先不会自己去尝试家在这个类，而是把这个请求为派给父类加载器去完成，每一个层次的类加载器都是如此，因此所有的家在请求最终都应该传送到最顶层的启动类加载器中，只有当父类加载器反馈自己无法完成加载请求（它的搜索范围中没有找到所需要的类）时，子加载器才会尝试自己去完成加载。<br>使用双亲委派模型来组织类加载器之间的关系，一个显而易见的好处就是 Java 中的类随着它的类加载器一起举杯了一种带有优先级的层次关系。例如类 java.lang.Object，它存放在 rt.jar 之中，无论哪一个类加载器要家在这个类，最终都是委派给处于模型最顶层的启动类加载器进行加载，因此 Object 类在程序的各种类加载器环境中都能够保证是同一个类。反之，如果没有使用双薪委派模型，都由各个类加载器自行去加载的话，如果用户自己也编写了一个名为 java.lang.Object 的类，并放在程序的 ClassPath 中，那系统中就会出现多个不同的 Object 类，Java 类型体系中最基础的行为也就无从保证，应用程序将会变得一片混乱。<br>可以来看下双亲委派模型的代码实现</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">/**
     * Loads the class with the specified &lt;a href="#name">binary name&lt;/a>.  The
     * default implementation of this method searches for classes in the
     * following order:
     *
     * &lt;ol>
     *
     *   &lt;li>&lt;p> Invoke &#123;@link #findLoadedClass(String)&#125; to check if the class
     *   has already been loaded.  &lt;/p>&lt;/li>
     *
     *   &lt;li>&lt;p> Invoke the &#123;@link #loadClass(String) &lt;tt>loadClass&lt;/tt>&#125; method
     *   on the parent class loader.  If the parent is &lt;tt>null&lt;/tt> the class
     *   loader built-in to the virtual machine is used, instead.  &lt;/p>&lt;/li>
     *
     *   &lt;li>&lt;p> Invoke the &#123;@link #findClass(String)&#125; method to find the
     *   class.  &lt;/p>&lt;/li>
     *
     * &lt;/ol>
     *
     * &lt;p> If the class was found using the above steps, and the
     * &lt;tt>resolve&lt;/tt> flag is true, this method will then invoke the &#123;@link
     * #resolveClass(Class)&#125; method on the resulting &lt;tt>Class&lt;/tt> object.
     *
     * &lt;p> Subclasses of &lt;tt>ClassLoader&lt;/tt> are encouraged to override &#123;@link
     * #findClass(String)&#125;, rather than this method.  &lt;/p>
     *
     * &lt;p> Unless overridden, this method synchronizes on the result of
     * &#123;@link #getClassLoadingLock &lt;tt>getClassLoadingLock&lt;/tt>&#125; method
     * during the entire class loading process.
     *
     * @param  name
     *         The &lt;a href="#name">binary name&lt;/a> of the class
     *
     * @param  resolve
     *         If &lt;tt>true&lt;/tt> then resolve the class
     *
     * @return  The resulting &lt;tt>Class&lt;/tt> object
     *
     * @throws  ClassNotFoundException
     *          If the class could not be found
     */</span>
    <span class="token keyword">protected</span> <span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span> <span class="token function">loadClass</span><span class="token punctuation">(</span><span class="token class-name">String</span> name<span class="token punctuation">,</span> <span class="token keyword">boolean</span> resolve<span class="token punctuation">)</span>
        <span class="token keyword">throws</span> <span class="token class-name">ClassNotFoundException</span>
    <span class="token punctuation">&#123;</span>
        <span class="token keyword">synchronized</span> <span class="token punctuation">(</span><span class="token function">getClassLoadingLock</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token comment">// First, check if the class has already been loaded</span>
            <span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span> c <span class="token operator">=</span> <span class="token function">findLoadedClass</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>c <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">long</span> t0 <span class="token operator">=</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">nanoTime</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">if</span> <span class="token punctuation">(</span>parent <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        <span class="token comment">// 委托父类加载</span>
                        c <span class="token operator">=</span> parent<span class="token punctuation">.</span><span class="token function">loadClass</span><span class="token punctuation">(</span>name<span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                        <span class="token comment">// 使用启动类加载器</span>
                        c <span class="token operator">=</span> <span class="token function">findBootstrapClassOrNull</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">ClassNotFoundException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token comment">// ClassNotFoundException thrown if class not found</span>
                    <span class="token comment">// from the non-null parent class loader</span>
                <span class="token punctuation">&#125;</span>

                <span class="token keyword">if</span> <span class="token punctuation">(</span>c <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token comment">// If still not found, then invoke findClass in order</span>
                    <span class="token comment">// to find the class.</span>
                    <span class="token keyword">long</span> t1 <span class="token operator">=</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">nanoTime</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token comment">// 调用自己的 findClass() 方法尝试进行加载</span>
                    c <span class="token operator">=</span> <span class="token function">findClass</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span>

                    <span class="token comment">// this is the defining class loader; record the stats</span>
                    <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>misc<span class="token punctuation">.</span></span>PerfCounter</span><span class="token punctuation">.</span><span class="token function">getParentDelegationTime</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">addTime</span><span class="token punctuation">(</span>t1 <span class="token operator">-</span> t0<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>misc<span class="token punctuation">.</span></span>PerfCounter</span><span class="token punctuation">.</span><span class="token function">getFindClassTime</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">addElapsedTimeFrom</span><span class="token punctuation">(</span>t1<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>misc<span class="token punctuation">.</span></span>PerfCounter</span><span class="token punctuation">.</span><span class="token function">getFindClasses</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">increment</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>resolve<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token function">resolveClass</span><span class="token punctuation">(</span>c<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
            <span class="token keyword">return</span> c<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="破坏双亲委派"><a href="#破坏双亲委派" class="headerlink" title="破坏双亲委派"></a>破坏双亲委派</h3><p>关于破坏双亲委派模型，第一次是在 JDK1.2 之后引入了双亲委派模型之前，那么在那之前已经有了类加载器，所以java.lang.ClassLoader 中添加了一个 protected 方法 findClass()，并引导用户编写的类加载逻辑时尽可能去重写这个方法，而不是在 loadClass()中编写代码。这个跟上面的逻辑其实类似，当父类加载失败，会调用 findClass()来完成加载；第二次是因为这个模型本身还有一些不足之处，比如 SPI 这种，所以有设计了线程下上下文类加载器(Thread Context ClassLoader)。这个类加载器可以通过 java.lang.Thread 类的 java.lang.Thread#setContextClassLoader() 进行设置，然后第三种是为了追求程序动态性，这里有涉及到了 osgi 等概念，就不展开了</p>
]]></content>
      <categories>
        <category>Java</category>
      </categories>
      <tags>
        <tag>Java</tag>
        <tag>类加载</tag>
        <tag>加载</tag>
        <tag>验证</tag>
        <tag>准备</tag>
        <tag>解析</tag>
        <tag>初始化</tag>
        <tag>链接</tag>
        <tag>双亲委派</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊 RocketMQ 的 Broker 源码</title>
    <url>/2020/07/19/%E8%81%8A%E8%81%8A-RocketMQ-%E7%9A%84-Broker-%E6%BA%90%E7%A0%81/</url>
    <content><![CDATA[<p>broker 的启动形式有点类似于 NameServer，都是服务类型的，跟 Consumer 差别比较大，</p>
<p>首先是org.apache.rocketmq.broker.BrokerStartup中的 main 函数，org.apache.rocketmq.broker.BrokerStartup#createBrokerController基本就是读取参数，这里差点把最核心的初始化给漏了，</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">final</span> <span class="token class-name">BrokerController</span> controller <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">BrokerController</span><span class="token punctuation">(</span>
                brokerConfig<span class="token punctuation">,</span>
                nettyServerConfig<span class="token punctuation">,</span>
                nettyClientConfig<span class="token punctuation">,</span>
                messageStoreConfig<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token comment">// remember all configs to prevent discard</span>
            controller<span class="token punctuation">.</span><span class="token function">getConfiguration</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">registerConfig</span><span class="token punctuation">(</span>properties<span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token keyword">boolean</span> initResult <span class="token operator">=</span> controller<span class="token punctuation">.</span><span class="token function">initialize</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>前面是以 broker 配置，netty 的服务端和客户端配置，以及消息存储配置在实例化 BrokerController，然后就是初始化了</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">initialize</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">CloneNotSupportedException</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">boolean</span> result <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>topicConfigManager<span class="token punctuation">.</span><span class="token function">load</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        result <span class="token operator">=</span> result <span class="token operator">&amp;&amp;</span> <span class="token keyword">this</span><span class="token punctuation">.</span>consumerOffsetManager<span class="token punctuation">.</span><span class="token function">load</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        result <span class="token operator">=</span> result <span class="token operator">&amp;&amp;</span> <span class="token keyword">this</span><span class="token punctuation">.</span>subscriptionGroupManager<span class="token punctuation">.</span><span class="token function">load</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        result <span class="token operator">=</span> result <span class="token operator">&amp;&amp;</span> <span class="token keyword">this</span><span class="token punctuation">.</span>consumerFilterManager<span class="token punctuation">.</span><span class="token function">load</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>前面这些就是各个配置的 load 了，然后是个我认为比较重要的部分messageStore 的实例化，</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">if</span> <span class="token punctuation">(</span>result<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>messageStore <span class="token operator">=</span>
            <span class="token keyword">new</span> <span class="token class-name">DefaultMessageStore</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>messageStoreConfig<span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>brokerStatsManager<span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>messageArrivingListener<span class="token punctuation">,</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>brokerConfig<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>messageStoreConfig<span class="token punctuation">.</span><span class="token function">isEnableDLegerCommitLog</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">DLedgerRoleChangeHandler</span> roleChangeHandler <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">DLedgerRoleChangeHandler</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token class-name">DefaultMessageStore</span><span class="token punctuation">)</span> messageStore<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token class-name">DLedgerCommitLog</span><span class="token punctuation">)</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token class-name">DefaultMessageStore</span><span class="token punctuation">)</span> messageStore<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getCommitLog</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getdLedgerServer</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getdLedgerLeaderElector</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">addRoleChangeHandler</span><span class="token punctuation">(</span>roleChangeHandler<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>brokerStats <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">BrokerStats</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token class-name">DefaultMessageStore</span><span class="token punctuation">)</span> <span class="token keyword">this</span><span class="token punctuation">.</span>messageStore<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">//load plugin</span>
        <span class="token class-name">MessageStorePluginContext</span> context <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">MessageStorePluginContext</span><span class="token punctuation">(</span>messageStoreConfig<span class="token punctuation">,</span> brokerStatsManager<span class="token punctuation">,</span> messageArrivingListener<span class="token punctuation">,</span> brokerConfig<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>messageStore <span class="token operator">=</span> <span class="token class-name">MessageStoreFactory</span><span class="token punctuation">.</span><span class="token function">build</span><span class="token punctuation">(</span>context<span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>messageStore<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>messageStore<span class="token punctuation">.</span><span class="token function">getDispatcherList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">addFirst</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">CommitLogDispatcherCalcBitMap</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>brokerConfig<span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>consumerFilterManager<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">IOException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        result <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
        log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"Failed to initialize"</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>

result <span class="token operator">=</span> result <span class="token operator">&amp;&amp;</span> <span class="token keyword">this</span><span class="token punctuation">.</span>messageStore<span class="token punctuation">.</span><span class="token function">load</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>先是实例化，实例化构造函数里的代码比较重要，重点看一下</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">DefaultMessageStore</span><span class="token punctuation">(</span><span class="token keyword">final</span> <span class="token class-name">MessageStoreConfig</span> messageStoreConfig<span class="token punctuation">,</span> <span class="token keyword">final</span> <span class="token class-name">BrokerStatsManager</span> brokerStatsManager<span class="token punctuation">,</span>
        <span class="token keyword">final</span> <span class="token class-name">MessageArrivingListener</span> messageArrivingListener<span class="token punctuation">,</span> <span class="token keyword">final</span> <span class="token class-name">BrokerConfig</span> brokerConfig<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">IOException</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>messageArrivingListener <span class="token operator">=</span> messageArrivingListener<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>brokerConfig <span class="token operator">=</span> brokerConfig<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>messageStoreConfig <span class="token operator">=</span> messageStoreConfig<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>brokerStatsManager <span class="token operator">=</span> brokerStatsManager<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>allocateMappedFileService <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">AllocateMappedFileService</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>messageStoreConfig<span class="token punctuation">.</span><span class="token function">isEnableDLegerCommitLog</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>commitLog <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">DLedgerCommitLog</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>commitLog <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">CommitLog</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>consumeQueueTable <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ConcurrentHashMap</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token number">32</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">this</span><span class="token punctuation">.</span>flushConsumeQueueService <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">FlushConsumeQueueService</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>cleanCommitLogService <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">CleanCommitLogService</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>cleanConsumeQueueService <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">CleanConsumeQueueService</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>storeStatsService <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">StoreStatsService</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>indexService <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">IndexService</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>messageStoreConfig<span class="token punctuation">.</span><span class="token function">isEnableDLegerCommitLog</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>haService <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">HAService</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>haService <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>reputMessageService <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ReputMessageService</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">this</span><span class="token punctuation">.</span>scheduleMessageService <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ScheduleMessageService</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">this</span><span class="token punctuation">.</span>transientStorePool <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">TransientStorePool</span><span class="token punctuation">(</span>messageStoreConfig<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span>messageStoreConfig<span class="token punctuation">.</span><span class="token function">isTransientStorePoolEnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>transientStorePool<span class="token punctuation">.</span><span class="token function">init</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">this</span><span class="token punctuation">.</span>allocateMappedFileService<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">this</span><span class="token punctuation">.</span>indexService<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">this</span><span class="token punctuation">.</span>dispatcherList <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">LinkedList</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>dispatcherList<span class="token punctuation">.</span><span class="token function">addLast</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">CommitLogDispatcherBuildConsumeQueue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>dispatcherList<span class="token punctuation">.</span><span class="token function">addLast</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">CommitLogDispatcherBuildIndex</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token class-name">File</span> file <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">File</span><span class="token punctuation">(</span><span class="token class-name">StorePathConfigHelper</span><span class="token punctuation">.</span><span class="token function">getLockFile</span><span class="token punctuation">(</span>messageStoreConfig<span class="token punctuation">.</span><span class="token function">getStorePathRootDir</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">MappedFile</span><span class="token punctuation">.</span><span class="token function">ensureDirOK</span><span class="token punctuation">(</span>file<span class="token punctuation">.</span><span class="token function">getParent</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        lockFile <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">RandomAccessFile</span><span class="token punctuation">(</span>file<span class="token punctuation">,</span> <span class="token string">"rw"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>这里面有很多类，不过先把从构造函数里传进来的忽略下，接下来就是 <code>AllocateMappedFileService</code> 这个service，前面看过文章的可能会根据上面的代码猜到，这也是个 ServiceThread，如果是对RocketMQ 有所了解的可能从名字可以看出这个类是关于 RocketMQ 消息怎么落盘的，当需要创建MappedFile时（在MapedFileQueue.getLastMapedFile方法中），向该线程的requestQueue队列中放入AllocateRequest请求对象，该线程会在后台监听该队列，并在后台创建MapedFile对象，即同时创建了物理文件。然后是创建了 IndexService 服务线程，用来给创建索引；还有是FlushConsumeQueueService是将ConsumeQueue 刷入磁盘；CleanCommitLogService用来清理过期的 CommitLog，默认是 72 小时以上；CleanConsumeQueueService是将小于最新的 CommitLog 偏移量的 ConsumeQueue 清理掉；StoreStatsService是储存统计服务；HAService用于CommitLog 的主备同步；ScheduleMessageService用于定时消息；还有就是这个ReputMessageService非常重要，就是由它实现了将 CommitLog 以 topic+queue 纬度构建 ConsumeQueue，后面TransientStorePool是异步刷盘时的存储buffer，也可以从后面的判断中看出来</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">isTransientStorePoolEnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> transientStorePoolEnable <span class="token operator">&amp;&amp;</span> <span class="token class-name">FlushDiskType</span><span class="token punctuation">.</span>ASYNC_FLUSH <span class="token operator">==</span> <span class="token function">getFlushDiskType</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
            <span class="token operator">&amp;&amp;</span> <span class="token class-name">BrokerRole</span><span class="token punctuation">.</span>SLAVE <span class="token operator">!=</span> <span class="token function">getBrokerRole</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p>再然后就是启动两个服务线程，dispatcherList是为CommitLog文件转发请求，差不多这个初始化就这些内容。</p>
<p>然后回到外层，下面是主备切换的配置，然后是数据统计，接着是存储插件加载，然后是往转发器链表里再加一个过滤器</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">if</span> <span class="token punctuation">(</span>messageStoreConfig<span class="token punctuation">.</span><span class="token function">isEnableDLegerCommitLog</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">DLedgerRoleChangeHandler</span> roleChangeHandler <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">DLedgerRoleChangeHandler</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token class-name">DefaultMessageStore</span><span class="token punctuation">)</span> messageStore<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token class-name">DLedgerCommitLog</span><span class="token punctuation">)</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token class-name">DefaultMessageStore</span><span class="token punctuation">)</span> messageStore<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getCommitLog</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getdLedgerServer</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getdLedgerLeaderElector</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">addRoleChangeHandler</span><span class="token punctuation">(</span>roleChangeHandler<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>brokerStats <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">BrokerStats</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token class-name">DefaultMessageStore</span><span class="token punctuation">)</span> <span class="token keyword">this</span><span class="token punctuation">.</span>messageStore<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">//load plugin</span>
        <span class="token class-name">MessageStorePluginContext</span> context <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">MessageStorePluginContext</span><span class="token punctuation">(</span>messageStoreConfig<span class="token punctuation">,</span> brokerStatsManager<span class="token punctuation">,</span> messageArrivingListener<span class="token punctuation">,</span> brokerConfig<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>messageStore <span class="token operator">=</span> <span class="token class-name">MessageStoreFactory</span><span class="token punctuation">.</span><span class="token function">build</span><span class="token punctuation">(</span>context<span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>messageStore<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>messageStore<span class="token punctuation">.</span><span class="token function">getDispatcherList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">addFirst</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">CommitLogDispatcherCalcBitMap</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>brokerConfig<span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>consumerFilterManager<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>接下来就是org.apache.rocketmq.store.MessageStore#load的过程了，</p>
<ol>
<li>调用ScheduleMessageService.load方法，初始化延迟级别列表。将这些级别（”1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h”）的延时存入延迟级别delayLevelTable：ConcurrentHashMap&lt;Integer /* level */, Long/* delay timeMillis */&gt;变量中，例如1s的kv值为1:1000,5s的kv值为2:5000，key值依次类推；每个延迟级别即为一个队列。</li>
</ol>
<p>2)调用CommitLog.load方法，在此方法中调用MapedFileQueue.load方法，将$HOME /store/commitlog目录下的所有文件加载到MapedFileQueue的List<MapedFile>变量中；</p>
<p>3)调用DefaultMessageStore.loadConsumeQueue方法加载consumequeue文件数据到DefaultMessageStore.consumeQueueTable集合中。</p>
<p>初始化StoreCheckPoint对象，加载$HOME/store/checkpoint文件，该文件记录三个字段值，分别是物理队列消息时间戳、逻辑队列消息时间戳、索引队列消息时间戳。</p>
<p>调用IndexService.load方法加载$HOME/store/index目录下的文件。对该目录下的每个文件初始化一个IndexFile对象。然后调用IndexFile对象的load方法将IndexHeader加载到对象的变量中；再根据检查是否存在abort文件，若有存在abort文件，则表示Broker表示上次是异常退出的，则检查checkpoint的indexMsgTimestamp字段值是否小于IndexHeader的endTimestamp值，indexMsgTimestamp值表示最后刷盘的时间，若小于则表示在最后刷盘之后在该文件中还创建了索引，则要删除该Index文件，否则将该IndexFile对象放入indexFileList:ArrayList<IndexFile>索引文件集合中。</p>
<p>然后调用org.apache.rocketmq.store.DefaultMessageStore#recover恢复，前面有根据<code>boolean lastExitOK = !this.isTempFileExist();</code>临时文件是否存在来判断上一次是否正常退出，根据这个状态来选择什么恢复策略</p>
<p>接下去是初始化 Netty 服务端，初始化发送消息线程池（sendMessageExecutor）、拉取消息线程池（pullMessageExecutor）、管理Broker线程池（adminBrokerExecutor）、客户端管理线程池（clientManageExecutor），注册事件处理器，包括发送消息事件处理器（SendMessageProcessor）、拉取消息事件处理器、查询消息事件处理器（QueryMessageProcessor，包括客户端的心跳事件、注销事件、获取消费者列表事件、更新更新和查询消费进度consumerOffset）、客户端管理事件处理器（ClientManageProcessor）、结束事务处理器（EndTransactionProcessor）、默认事件处理器（AdminBrokerProcessor），然后是定时任务</p>
<p><code>BrokerController.this.getBrokerStats().record();</code> 记录 Broker 状态</p>
<p><code>BrokerController.this.consumerOffsetManager.persist();</code> 持久化consumerOffset</p>
<p><code>BrokerController.this.consumerFilterManager.persist();</code>持久化consumerFilter</p>
<p><code>BrokerController.this.protectBroker();</code> 保护 broker，消费慢，不让继续投递</p>
<p><code>BrokerController.this.printWaterMark();</code> 打印水位</p>
<p><code>log.info(&quot;dispatch behind commit log &#123;&#125; bytes&quot;, BrokerController.this.getMessageStore().dispatchBehindBytes());</code> 检查落后程度</p>
<p><code>BrokerController.this.brokerOuterAPI.fetchNameServerAddr();</code> 定时获取 nameserver</p>
<p><code>BrokerController.this.printMasterAndSlaveDiff();</code> 打印主从不一致</p>
<p>然后是 tsl，初始化事务消息，初始化 RPCHook</p>
<p>请把害怕打到公屏上🤦‍♂️，从线程池名字和调用的方法应该可以看出大部分的用途</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">this</span><span class="token punctuation">.</span>remotingServer <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">NettyRemotingServer</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>nettyServerConfig<span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>clientHousekeepingService<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">NettyServerConfig</span> fastConfig <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">NettyServerConfig</span><span class="token punctuation">)</span> <span class="token keyword">this</span><span class="token punctuation">.</span>nettyServerConfig<span class="token punctuation">.</span><span class="token function">clone</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            fastConfig<span class="token punctuation">.</span><span class="token function">setListenPort</span><span class="token punctuation">(</span>nettyServerConfig<span class="token punctuation">.</span><span class="token function">getListenPort</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-</span> <span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>fastRemotingServer <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">NettyRemotingServer</span><span class="token punctuation">(</span>fastConfig<span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>clientHousekeepingService<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>sendMessageExecutor <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">BrokerFixedThreadPoolExecutor</span><span class="token punctuation">(</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>brokerConfig<span class="token punctuation">.</span><span class="token function">getSendMessageThreadPoolNums</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>brokerConfig<span class="token punctuation">.</span><span class="token function">getSendMessageThreadPoolNums</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
                <span class="token number">1000</span> <span class="token operator">*</span> <span class="token number">60</span><span class="token punctuation">,</span>
                <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>MILLISECONDS<span class="token punctuation">,</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>sendThreadPoolQueue<span class="token punctuation">,</span>
                <span class="token keyword">new</span> <span class="token class-name">ThreadFactoryImpl</span><span class="token punctuation">(</span><span class="token string">"SendMessageThread_"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token keyword">this</span><span class="token punctuation">.</span>pullMessageExecutor <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">BrokerFixedThreadPoolExecutor</span><span class="token punctuation">(</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>brokerConfig<span class="token punctuation">.</span><span class="token function">getPullMessageThreadPoolNums</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>brokerConfig<span class="token punctuation">.</span><span class="token function">getPullMessageThreadPoolNums</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
                <span class="token number">1000</span> <span class="token operator">*</span> <span class="token number">60</span><span class="token punctuation">,</span>
                <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>MILLISECONDS<span class="token punctuation">,</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>pullThreadPoolQueue<span class="token punctuation">,</span>
                <span class="token keyword">new</span> <span class="token class-name">ThreadFactoryImpl</span><span class="token punctuation">(</span><span class="token string">"PullMessageThread_"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token keyword">this</span><span class="token punctuation">.</span>replyMessageExecutor <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">BrokerFixedThreadPoolExecutor</span><span class="token punctuation">(</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>brokerConfig<span class="token punctuation">.</span><span class="token function">getProcessReplyMessageThreadPoolNums</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>brokerConfig<span class="token punctuation">.</span><span class="token function">getProcessReplyMessageThreadPoolNums</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
                <span class="token number">1000</span> <span class="token operator">*</span> <span class="token number">60</span><span class="token punctuation">,</span>
                <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>MILLISECONDS<span class="token punctuation">,</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>replyThreadPoolQueue<span class="token punctuation">,</span>
                <span class="token keyword">new</span> <span class="token class-name">ThreadFactoryImpl</span><span class="token punctuation">(</span><span class="token string">"ProcessReplyMessageThread_"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token keyword">this</span><span class="token punctuation">.</span>queryMessageExecutor <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">BrokerFixedThreadPoolExecutor</span><span class="token punctuation">(</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>brokerConfig<span class="token punctuation">.</span><span class="token function">getQueryMessageThreadPoolNums</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>brokerConfig<span class="token punctuation">.</span><span class="token function">getQueryMessageThreadPoolNums</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
                <span class="token number">1000</span> <span class="token operator">*</span> <span class="token number">60</span><span class="token punctuation">,</span>
                <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>MILLISECONDS<span class="token punctuation">,</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>queryThreadPoolQueue<span class="token punctuation">,</span>
                <span class="token keyword">new</span> <span class="token class-name">ThreadFactoryImpl</span><span class="token punctuation">(</span><span class="token string">"QueryMessageThread_"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token keyword">this</span><span class="token punctuation">.</span>adminBrokerExecutor <span class="token operator">=</span>
                <span class="token class-name">Executors</span><span class="token punctuation">.</span><span class="token function">newFixedThreadPool</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>brokerConfig<span class="token punctuation">.</span><span class="token function">getAdminBrokerThreadPoolNums</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">ThreadFactoryImpl</span><span class="token punctuation">(</span>
                    <span class="token string">"AdminBrokerThread_"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token keyword">this</span><span class="token punctuation">.</span>clientManageExecutor <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">(</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>brokerConfig<span class="token punctuation">.</span><span class="token function">getClientManageThreadPoolNums</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>brokerConfig<span class="token punctuation">.</span><span class="token function">getClientManageThreadPoolNums</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
                <span class="token number">1000</span> <span class="token operator">*</span> <span class="token number">60</span><span class="token punctuation">,</span>
                <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>MILLISECONDS<span class="token punctuation">,</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>clientManagerThreadPoolQueue<span class="token punctuation">,</span>
                <span class="token keyword">new</span> <span class="token class-name">ThreadFactoryImpl</span><span class="token punctuation">(</span><span class="token string">"ClientManageThread_"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token keyword">this</span><span class="token punctuation">.</span>heartbeatExecutor <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">BrokerFixedThreadPoolExecutor</span><span class="token punctuation">(</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>brokerConfig<span class="token punctuation">.</span><span class="token function">getHeartbeatThreadPoolNums</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>brokerConfig<span class="token punctuation">.</span><span class="token function">getHeartbeatThreadPoolNums</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
                <span class="token number">1000</span> <span class="token operator">*</span> <span class="token number">60</span><span class="token punctuation">,</span>
                <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>MILLISECONDS<span class="token punctuation">,</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>heartbeatThreadPoolQueue<span class="token punctuation">,</span>
                <span class="token keyword">new</span> <span class="token class-name">ThreadFactoryImpl</span><span class="token punctuation">(</span><span class="token string">"HeartbeatThread_"</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token keyword">this</span><span class="token punctuation">.</span>endTransactionExecutor <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">BrokerFixedThreadPoolExecutor</span><span class="token punctuation">(</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>brokerConfig<span class="token punctuation">.</span><span class="token function">getEndTransactionThreadPoolNums</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>brokerConfig<span class="token punctuation">.</span><span class="token function">getEndTransactionThreadPoolNums</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
                <span class="token number">1000</span> <span class="token operator">*</span> <span class="token number">60</span><span class="token punctuation">,</span>
                <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>MILLISECONDS<span class="token punctuation">,</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>endTransactionThreadPoolQueue<span class="token punctuation">,</span>
                <span class="token keyword">new</span> <span class="token class-name">ThreadFactoryImpl</span><span class="token punctuation">(</span><span class="token string">"EndTransactionThread_"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token keyword">this</span><span class="token punctuation">.</span>consumerManageExecutor <span class="token operator">=</span>
                <span class="token class-name">Executors</span><span class="token punctuation">.</span><span class="token function">newFixedThreadPool</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>brokerConfig<span class="token punctuation">.</span><span class="token function">getConsumerManageThreadPoolNums</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">ThreadFactoryImpl</span><span class="token punctuation">(</span>
                    <span class="token string">"ConsumerManageThread_"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">registerProcessor</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token keyword">final</span> <span class="token keyword">long</span> initialDelay <span class="token operator">=</span> <span class="token class-name">UtilAll</span><span class="token punctuation">.</span><span class="token function">computeNextMorningTimeMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">currentTimeMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">final</span> <span class="token keyword">long</span> period <span class="token operator">=</span> <span class="token number">1000</span> <span class="token operator">*</span> <span class="token number">60</span> <span class="token operator">*</span> <span class="token number">60</span> <span class="token operator">*</span> <span class="token number">24</span><span class="token punctuation">;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>scheduledExecutorService<span class="token punctuation">.</span><span class="token function">scheduleAtFixedRate</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Runnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token annotation punctuation">@Override</span>
                <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                        <span class="token class-name">BrokerController</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getBrokerStats</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token keyword">record</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Throwable</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"schedule record error."</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span><span class="token punctuation">,</span> initialDelay<span class="token punctuation">,</span> period<span class="token punctuation">,</span> <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>MILLISECONDS<span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token keyword">this</span><span class="token punctuation">.</span>scheduledExecutorService<span class="token punctuation">.</span><span class="token function">scheduleAtFixedRate</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Runnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token annotation punctuation">@Override</span>
                <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                        <span class="token class-name">BrokerController</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>consumerOffsetManager<span class="token punctuation">.</span><span class="token function">persist</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Throwable</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"schedule persist consumerOffset error."</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span><span class="token punctuation">,</span> <span class="token number">1000</span> <span class="token operator">*</span> <span class="token number">10</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>brokerConfig<span class="token punctuation">.</span><span class="token function">getFlushConsumerOffsetInterval</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>MILLISECONDS<span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token keyword">this</span><span class="token punctuation">.</span>scheduledExecutorService<span class="token punctuation">.</span><span class="token function">scheduleAtFixedRate</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Runnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token annotation punctuation">@Override</span>
                <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                        <span class="token class-name">BrokerController</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>consumerFilterManager<span class="token punctuation">.</span><span class="token function">persist</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Throwable</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"schedule persist consumer filter error."</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span><span class="token punctuation">,</span> <span class="token number">1000</span> <span class="token operator">*</span> <span class="token number">10</span><span class="token punctuation">,</span> <span class="token number">1000</span> <span class="token operator">*</span> <span class="token number">10</span><span class="token punctuation">,</span> <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>MILLISECONDS<span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token keyword">this</span><span class="token punctuation">.</span>scheduledExecutorService<span class="token punctuation">.</span><span class="token function">scheduleAtFixedRate</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Runnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token annotation punctuation">@Override</span>
                <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                        <span class="token class-name">BrokerController</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">protectBroker</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Throwable</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"protectBroker error."</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>MINUTES<span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token keyword">this</span><span class="token punctuation">.</span>scheduledExecutorService<span class="token punctuation">.</span><span class="token function">scheduleAtFixedRate</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Runnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token annotation punctuation">@Override</span>
                <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                        <span class="token class-name">BrokerController</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">printWaterMark</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Throwable</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"printWaterMark error."</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>SECONDS<span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token keyword">this</span><span class="token punctuation">.</span>scheduledExecutorService<span class="token punctuation">.</span><span class="token function">scheduleAtFixedRate</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Runnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>

                <span class="token annotation punctuation">@Override</span>
                <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                        log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"dispatch behind commit log &#123;&#125; bytes"</span><span class="token punctuation">,</span> <span class="token class-name">BrokerController</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getMessageStore</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">dispatchBehindBytes</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Throwable</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"schedule dispatchBehindBytes error."</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span><span class="token punctuation">,</span> <span class="token number">1000</span> <span class="token operator">*</span> <span class="token number">10</span><span class="token punctuation">,</span> <span class="token number">1000</span> <span class="token operator">*</span> <span class="token number">60</span><span class="token punctuation">,</span> <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>MILLISECONDS<span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>brokerConfig<span class="token punctuation">.</span><span class="token function">getNamesrvAddr</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>brokerOuterAPI<span class="token punctuation">.</span><span class="token function">updateNameServerAddressList</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>brokerConfig<span class="token punctuation">.</span><span class="token function">getNamesrvAddr</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"Set user specified name server address: &#123;&#125;"</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>brokerConfig<span class="token punctuation">.</span><span class="token function">getNamesrvAddr</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>brokerConfig<span class="token punctuation">.</span><span class="token function">isFetchNamesrvAddrByAddressServer</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">this</span><span class="token punctuation">.</span>scheduledExecutorService<span class="token punctuation">.</span><span class="token function">scheduleAtFixedRate</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Runnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>

                    <span class="token annotation punctuation">@Override</span>
                    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                            <span class="token class-name">BrokerController</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>brokerOuterAPI<span class="token punctuation">.</span><span class="token function">fetchNameServerAddr</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Throwable</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                            log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"ScheduledTask fetchNameServerAddr exception"</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token punctuation">&#125;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span><span class="token punctuation">,</span> <span class="token number">1000</span> <span class="token operator">*</span> <span class="token number">10</span><span class="token punctuation">,</span> <span class="token number">1000</span> <span class="token operator">*</span> <span class="token number">60</span> <span class="token operator">*</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>MILLISECONDS<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>

            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>messageStoreConfig<span class="token punctuation">.</span><span class="token function">isEnableDLegerCommitLog</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">BrokerRole</span><span class="token punctuation">.</span>SLAVE <span class="token operator">==</span> <span class="token keyword">this</span><span class="token punctuation">.</span>messageStoreConfig<span class="token punctuation">.</span><span class="token function">getBrokerRole</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>messageStoreConfig<span class="token punctuation">.</span><span class="token function">getHaMasterAddress</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">!=</span> <span class="token keyword">null</span> <span class="token operator">&amp;&amp;</span> <span class="token keyword">this</span><span class="token punctuation">.</span>messageStoreConfig<span class="token punctuation">.</span><span class="token function">getHaMasterAddress</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">>=</span> <span class="token number">6</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        <span class="token keyword">this</span><span class="token punctuation">.</span>messageStore<span class="token punctuation">.</span><span class="token function">updateHaMasterAddress</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>messageStoreConfig<span class="token punctuation">.</span><span class="token function">getHaMasterAddress</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token keyword">this</span><span class="token punctuation">.</span>updateMasterHAServerAddrPeriodically <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                        <span class="token keyword">this</span><span class="token punctuation">.</span>updateMasterHAServerAddrPeriodically <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">this</span><span class="token punctuation">.</span>scheduledExecutorService<span class="token punctuation">.</span><span class="token function">scheduleAtFixedRate</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Runnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        <span class="token annotation punctuation">@Override</span>
                        <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                            <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                                <span class="token class-name">BrokerController</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">printMasterAndSlaveDiff</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Throwable</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"schedule printMasterAndSlaveDiff error."</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token punctuation">&#125;</span>
                        <span class="token punctuation">&#125;</span>
                    <span class="token punctuation">&#125;</span><span class="token punctuation">,</span> <span class="token number">1000</span> <span class="token operator">*</span> <span class="token number">10</span><span class="token punctuation">,</span> <span class="token number">1000</span> <span class="token operator">*</span> <span class="token number">60</span><span class="token punctuation">,</span> <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>MILLISECONDS<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span>

            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">TlsSystemConfig</span><span class="token punctuation">.</span>tlsMode <span class="token operator">!=</span> <span class="token class-name">TlsMode</span><span class="token punctuation">.</span>DISABLED<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token comment">// Register a listener to reload SslContext</span>
                <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                    fileWatchService <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">FileWatchService</span><span class="token punctuation">(</span>
                        <span class="token keyword">new</span> <span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token punctuation">&#123;</span>
                            <span class="token class-name">TlsSystemConfig</span><span class="token punctuation">.</span>tlsServerCertPath<span class="token punctuation">,</span>
                            <span class="token class-name">TlsSystemConfig</span><span class="token punctuation">.</span>tlsServerKeyPath<span class="token punctuation">,</span>
                            <span class="token class-name">TlsSystemConfig</span><span class="token punctuation">.</span>tlsServerTrustCertPath
                        <span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
                        <span class="token keyword">new</span> <span class="token class-name">FileWatchService<span class="token punctuation">.</span>Listener</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                            <span class="token keyword">boolean</span> certChanged<span class="token punctuation">,</span> keyChanged <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>

                            <span class="token annotation punctuation">@Override</span>
                            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">onChanged</span><span class="token punctuation">(</span><span class="token class-name">String</span> path<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                <span class="token keyword">if</span> <span class="token punctuation">(</span>path<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span><span class="token class-name">TlsSystemConfig</span><span class="token punctuation">.</span>tlsServerTrustCertPath<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                    log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"The trust certificate changed, reload the ssl context"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                                    <span class="token function">reloadServerSslContext</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                                <span class="token punctuation">&#125;</span>
                                <span class="token keyword">if</span> <span class="token punctuation">(</span>path<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span><span class="token class-name">TlsSystemConfig</span><span class="token punctuation">.</span>tlsServerCertPath<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                    certChanged <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
                                <span class="token punctuation">&#125;</span>
                                <span class="token keyword">if</span> <span class="token punctuation">(</span>path<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span><span class="token class-name">TlsSystemConfig</span><span class="token punctuation">.</span>tlsServerKeyPath<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                    keyChanged <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
                                <span class="token punctuation">&#125;</span>
                                <span class="token keyword">if</span> <span class="token punctuation">(</span>certChanged <span class="token operator">&amp;&amp;</span> keyChanged<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                    log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"The certificate and private key changed, reload the ssl context"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                                    certChanged <span class="token operator">=</span> keyChanged <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
                                    <span class="token function">reloadServerSslContext</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                                <span class="token punctuation">&#125;</span>
                            <span class="token punctuation">&#125;</span>

                            <span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">reloadServerSslContext</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                                <span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token class-name">NettyRemotingServer</span><span class="token punctuation">)</span> remotingServer<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">loadSslContext</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                                <span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token class-name">NettyRemotingServer</span><span class="token punctuation">)</span> fastRemotingServer<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">loadSslContext</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                            <span class="token punctuation">&#125;</span>
                        <span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token string">"FileWatchService created error, can't load the certificate dynamically"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span>
            <span class="token function">initialTransaction</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token function">initialAcl</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token function">initialRpcHooks</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">return</span> result<span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<p>Broker 启动过程</p>
<p>贴代码</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">Exception</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>messageStore <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>messageStore<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>remotingServer <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>remotingServer<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>fastRemotingServer <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>fastRemotingServer<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>fileWatchService <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>fileWatchService<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>brokerOuterAPI <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>brokerOuterAPI<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>pullRequestHoldService <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>pullRequestHoldService<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>clientHousekeepingService <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>clientHousekeepingService<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>filterServerManager <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>filterServerManager<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>messageStoreConfig<span class="token punctuation">.</span><span class="token function">isEnableDLegerCommitLog</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token function">startProcessorByHa</span><span class="token punctuation">(</span>messageStoreConfig<span class="token punctuation">.</span><span class="token function">getBrokerRole</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token function">handleSlaveSynchronize</span><span class="token punctuation">(</span>messageStoreConfig<span class="token punctuation">.</span><span class="token function">getBrokerRole</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">registerBrokerAll</span><span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">this</span><span class="token punctuation">.</span>scheduledExecutorService<span class="token punctuation">.</span><span class="token function">scheduleAtFixedRate</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Runnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>

            <span class="token annotation punctuation">@Override</span>
            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                    <span class="token class-name">BrokerController</span><span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">registerBrokerAll</span><span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">,</span> brokerConfig<span class="token punctuation">.</span><span class="token function">isForceRegister</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Throwable</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"registerBrokerAll Exception"</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">,</span> <span class="token number">1000</span> <span class="token operator">*</span> <span class="token number">10</span><span class="token punctuation">,</span> <span class="token class-name">Math</span><span class="token punctuation">.</span><span class="token function">max</span><span class="token punctuation">(</span><span class="token number">10000</span><span class="token punctuation">,</span> <span class="token class-name">Math</span><span class="token punctuation">.</span><span class="token function">min</span><span class="token punctuation">(</span>brokerConfig<span class="token punctuation">.</span><span class="token function">getRegisterNameServerPeriod</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">60000</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>MILLISECONDS<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>brokerStatsManager <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>brokerStatsManager<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>brokerFastFailure <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>brokerFastFailure<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>


    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>首先是启动messageStore，调用 start 方法，这里面又调用了一些代码</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">Exception</span> <span class="token punctuation">&#123;</span>

        lock <span class="token operator">=</span> lockFile<span class="token punctuation">.</span><span class="token function">getChannel</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">tryLock</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>lock <span class="token operator">==</span> <span class="token keyword">null</span> <span class="token operator">||</span> lock<span class="token punctuation">.</span><span class="token function">isShared</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">||</span> <span class="token operator">!</span>lock<span class="token punctuation">.</span><span class="token function">isValid</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">RuntimeException</span><span class="token punctuation">(</span><span class="token string">"Lock failed,MQ already started"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        lockFile<span class="token punctuation">.</span><span class="token function">getChannel</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">write</span><span class="token punctuation">(</span><span class="token class-name">ByteBuffer</span><span class="token punctuation">.</span><span class="token function">wrap</span><span class="token punctuation">(</span><span class="token string">"lock"</span><span class="token punctuation">.</span><span class="token function">getBytes</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        lockFile<span class="token punctuation">.</span><span class="token function">getChannel</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">force</span><span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#123;</span>
            <span class="token comment">/**
             * 1. Make sure the fast-forward messages to be truncated during the recovering according to the max physical offset of the commitlog;
             * 2. DLedger committedPos may be missing, so the maxPhysicalPosInLogicQueue maybe bigger that maxOffset returned by DLedgerCommitLog, just let it go;
             * 3. Calculate the reput offset according to the consume queue;
             * 4. Make sure the fall-behind messages to be dispatched before starting the commitlog, especially when the broker role are automatically changed.
             */</span>
            <span class="token keyword">long</span> maxPhysicalPosInLogicQueue <span class="token operator">=</span> commitLog<span class="token punctuation">.</span><span class="token function">getMinOffset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">ConcurrentMap</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">,</span> <span class="token class-name">ConsumeQueue</span><span class="token punctuation">></span></span> maps <span class="token operator">:</span> <span class="token keyword">this</span><span class="token punctuation">.</span>consumeQueueTable<span class="token punctuation">.</span><span class="token function">values</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">ConsumeQueue</span> logic <span class="token operator">:</span> maps<span class="token punctuation">.</span><span class="token function">values</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">if</span> <span class="token punctuation">(</span>logic<span class="token punctuation">.</span><span class="token function">getMaxPhysicOffset</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">></span> maxPhysicalPosInLogicQueue<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        maxPhysicalPosInLogicQueue <span class="token operator">=</span> logic<span class="token punctuation">.</span><span class="token function">getMaxPhysicOffset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>maxPhysicalPosInLogicQueue <span class="token operator">&lt;</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                maxPhysicalPosInLogicQueue <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>maxPhysicalPosInLogicQueue <span class="token operator">&lt;</span> <span class="token keyword">this</span><span class="token punctuation">.</span>commitLog<span class="token punctuation">.</span><span class="token function">getMinOffset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                maxPhysicalPosInLogicQueue <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>commitLog<span class="token punctuation">.</span><span class="token function">getMinOffset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token comment">/**
                 * This happens in following conditions:
                 * 1. If someone removes all the consumequeue files or the disk get damaged.
                 * 2. Launch a new broker, and copy the commitlog from other brokers.
                 *
                 * All the conditions has the same in common that the maxPhysicalPosInLogicQueue should be 0.
                 * If the maxPhysicalPosInLogicQueue is gt 0, there maybe something wrong.
                 */</span>
                log<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token string">"[TooSmallCqOffset] maxPhysicalPosInLogicQueue=&#123;&#125; clMinOffset=&#123;&#125;"</span><span class="token punctuation">,</span> maxPhysicalPosInLogicQueue<span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>commitLog<span class="token punctuation">.</span><span class="token function">getMinOffset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
            log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"[SetReputOffset] maxPhysicalPosInLogicQueue=&#123;&#125; clMinOffset=&#123;&#125; clMaxOffset=&#123;&#125; clConfirmedOffset=&#123;&#125;"</span><span class="token punctuation">,</span>
                maxPhysicalPosInLogicQueue<span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>commitLog<span class="token punctuation">.</span><span class="token function">getMinOffset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>commitLog<span class="token punctuation">.</span><span class="token function">getMaxOffset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>commitLog<span class="token punctuation">.</span><span class="token function">getConfirmOffset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>reputMessageService<span class="token punctuation">.</span><span class="token function">setReputFromOffset</span><span class="token punctuation">(</span>maxPhysicalPosInLogicQueue<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>reputMessageService<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token comment">/**
             *  1. Finish dispatching the messages fall behind, then to start other services.
             *  2. DLedger committedPos may be missing, so here just require dispatchBehindBytes &lt;= 0
             */</span>
            <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">dispatchBehindBytes</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&lt;=</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">break</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
                <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">1000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"Try to finish doing reput the messages fall behind during the starting, reputOffset=&#123;&#125; maxOffset=&#123;&#125; behind=&#123;&#125;"</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>reputMessageService<span class="token punctuation">.</span><span class="token function">getReputFromOffset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getMaxPhyOffset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">dispatchBehindBytes</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">recoverTopicQueueTable</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>messageStoreConfig<span class="token punctuation">.</span><span class="token function">isEnableDLegerCommitLog</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>haService<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">handleScheduleMessageService</span><span class="token punctuation">(</span>messageStoreConfig<span class="token punctuation">.</span><span class="token function">getBrokerRole</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

        <span class="token keyword">this</span><span class="token punctuation">.</span>flushConsumeQueueService<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>commitLog<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>storeStatsService<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">createTempFile</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">addScheduleTask</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>shutdown <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<p>调用DefaultMessageStore.start方法启动DefaultMessageStore对象中的一些服务线程。</p>
<ol>
<li>启动ReputMessageService服务线程</li>
<li>启动FlushConsumeQueueService服务线程；</li>
<li>调用CommitLog.start方法，启动CommitLog对象中的FlushCommitLogService线程服务，若是同步刷盘（SYNC_FLUSH）则是启动GroupCommitService线程服务；若是异步刷盘（ASYNC_FLUSH）则是启动FlushRealTimeService线程服务；</li>
<li>启动StoreStatsService线程服务；</li>
<li>启动定时清理任务</li>
</ol>
<p>然后是启动ClientHousekeepingService的 netty 服务端和客户端，然后是启动fileWatchService证书服务，接着启动BrokerOuterAPI中的NettyRemotingClient，即建立与NameServer的链接，用于自身Broker与其他模块的RPC功能调用；包括获取NameServer的地址、注册Broker、注销Broker、获取Topic配置、获取消息进度信息、获取订阅关系等RPC功能，然后是PullRequestHoldService服务线程，这个就是实现长轮询的，然后启动管家ClientHousekeepingService服务，负责扫描不活跃的生产者，消费者和 filter，启动FilterServerManager 过滤器服务管理，然后启动定时任务调用org.apache.rocketmq.broker.BrokerController#registerBrokerAll向所有 nameserver 注册 broker，最后是按需开启org.apache.rocketmq.store.stats.BrokerStatsManager和org.apache.rocketmq.broker.latency.BrokerFastFailure，基本上启动过程就完成了</p>
]]></content>
      <categories>
        <category>MQ</category>
        <category>RocketMQ</category>
        <category>消息队列</category>
        <category>RocketMQ</category>
        <category>中间件</category>
        <category>RocketMQ</category>
      </categories>
      <tags>
        <tag>MQ</tag>
        <tag>消息队列</tag>
        <tag>RocketMQ</tag>
        <tag>削峰填谷</tag>
        <tag>中间件</tag>
        <tag>源码解析</tag>
        <tag>Broker</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊 SpringBoot 自动装配</title>
    <url>/2021/07/11/%E8%81%8A%E8%81%8ASpringBoot-%E8%87%AA%E5%8A%A8%E8%A3%85%E9%85%8D/</url>
    <content><![CDATA[<p>springboot 自动装配调用链</p>
<p>springboot 相比 spring能更方便开发人员上手，比较重要的一点就是自动装配，大致来看下这个逻辑</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
		<span class="token class-name">SpringApplication</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">SpbDemoApplication</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">,</span> args<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>

	<span class="token comment">/**
	 * Static helper that can be used to run a &#123;@link SpringApplication&#125; from the
	 * specified source using default settings.
	 * @param primarySource the primary source to load
	 * @param args the application arguments (usually passed from a Java main method)
	 * @return the running &#123;@link ApplicationContext&#125;
	 */</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>然后就是上面调用的 run 方法</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token class-name">ConfigurableApplicationContext</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span> primarySource<span class="token punctuation">,</span> <span class="token class-name">String</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span> args<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">return</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span><span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token punctuation">&#123;</span> primarySource <span class="token punctuation">&#125;</span><span class="token punctuation">,</span> args<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">/**
 * Static helper that can be used to run a &#123;@link SpringApplication&#125; from the
 * specified sources using default settings and user supplied arguments.
 * @param primarySources the primary sources to load
 * @param args the application arguments (usually passed from a Java main method)
 * @return the running &#123;@link ApplicationContext&#125;
 */</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>继续往下看</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token class-name">ConfigurableApplicationContext</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span><span class="token punctuation">[</span><span class="token punctuation">]</span> primarySources<span class="token punctuation">,</span> <span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">SpringApplication</span><span class="token punctuation">(</span>primarySources<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span>args<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<span id="more"></span>
<p>调用SpringApplication的构造方法</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">/**
 * Create a new &#123;@link SpringApplication&#125; instance. The application context will load
 * beans from the specified primary sources (see &#123;@link SpringApplication class-level&#125;
 * documentation for details. The instance can be customized before calling
 * &#123;@link #run(String...)&#125;.
 * @param primarySources the primary bean sources
 * @see #run(Class, String[])
 * @see #SpringApplication(ResourceLoader, Class...)
 * @see #setSources(Set)
 */</span>

<span class="token keyword">public</span> <span class="token class-name">SpringApplication</span><span class="token punctuation">(</span><span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span> primarySources<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">this</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">,</span> primarySources<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">/**
 * Create a new &#123;@link SpringApplication&#125; instance. The application context will load
 * beans from the specified primary sources (see &#123;@link SpringApplication class-level&#125;
 * documentation for details. The instance can be customized before calling
 * &#123;@link #run(String...)&#125;.
 * @param resourceLoader the resource loader to use
 * @param primarySources the primary bean sources
 * @see #run(Class, String[])
 * @see #setSources(Set)
 */</span>
<span class="token annotation punctuation">@SuppressWarnings</span><span class="token punctuation">(</span><span class="token punctuation">&#123;</span> <span class="token string">"unchecked"</span><span class="token punctuation">,</span> <span class="token string">"rawtypes"</span> <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token class-name">SpringApplication</span><span class="token punctuation">(</span><span class="token class-name">ResourceLoader</span> resourceLoader<span class="token punctuation">,</span> <span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span> primarySources<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">this</span><span class="token punctuation">.</span>resourceLoader <span class="token operator">=</span> resourceLoader<span class="token punctuation">;</span>
	<span class="token class-name">Assert</span><span class="token punctuation">.</span><span class="token function">notNull</span><span class="token punctuation">(</span>primarySources<span class="token punctuation">,</span> <span class="token string">"PrimarySources must not be null"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token keyword">this</span><span class="token punctuation">.</span>primarySources <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">LinkedHashSet</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">asList</span><span class="token punctuation">(</span>primarySources<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token keyword">this</span><span class="token punctuation">.</span>webApplicationType <span class="token operator">=</span> <span class="token class-name">WebApplicationType</span><span class="token punctuation">.</span><span class="token function">deduceFromClasspath</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
   <span class="token comment">// 注意看这里的，通过 SpringFactories 获取</span>
	<span class="token keyword">this</span><span class="token punctuation">.</span>bootstrapRegistryInitializers <span class="token operator">=</span> <span class="token function">getBootstrapRegistryInitializersFromSpringFactories</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token function">setInitializers</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token class-name">Collection</span><span class="token punctuation">)</span> <span class="token function">getSpringFactoriesInstances</span><span class="token punctuation">(</span><span class="token class-name">ApplicationContextInitializer</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token function">setListeners</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token class-name">Collection</span><span class="token punctuation">)</span> <span class="token function">getSpringFactoriesInstances</span><span class="token punctuation">(</span><span class="token class-name">ApplicationListener</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token keyword">this</span><span class="token punctuation">.</span>mainApplicationClass <span class="token operator">=</span> <span class="token function">deduceMainApplicationClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这里就是重点了</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">private</span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">BootstrapRegistryInitializer</span><span class="token punctuation">></span></span> <span class="token function">getBootstrapRegistryInitializersFromSpringFactories</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	<span class="token class-name">ArrayList</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">BootstrapRegistryInitializer</span><span class="token punctuation">></span></span> initializers <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayList</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token function">getSpringFactoriesInstances</span><span class="token punctuation">(</span><span class="token class-name">Bootstrapper</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
			<span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span><span class="token punctuation">(</span>bootstrapper<span class="token punctuation">)</span> <span class="token operator">-></span> <span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token class-name">BootstrapRegistryInitializer</span><span class="token punctuation">)</span> bootstrapper<span class="token operator">::</span><span class="token function">initialize</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
			<span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span>initializers<span class="token operator">::</span><span class="token function">add</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	initializers<span class="token punctuation">.</span><span class="token function">addAll</span><span class="token punctuation">(</span><span class="token function">getSpringFactoriesInstances</span><span class="token punctuation">(</span><span class="token class-name">BootstrapRegistryInitializer</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token keyword">return</span> initializers<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">private</span> <span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">></span></span> <span class="token class-name">Collection</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">></span></span> <span class="token function">getSpringFactoriesInstances</span><span class="token punctuation">(</span><span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">></span></span> type<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">return</span> <span class="token function">getSpringFactoriesInstances</span><span class="token punctuation">(</span>type<span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span><span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>

<span class="token keyword">private</span> <span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">></span></span> <span class="token class-name">Collection</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">></span></span> <span class="token function">getSpringFactoriesInstances</span><span class="token punctuation">(</span><span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">></span></span> type<span class="token punctuation">,</span> <span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span><span class="token punctuation">[</span><span class="token punctuation">]</span> parameterTypes<span class="token punctuation">,</span> <span class="token class-name">Object</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span> args<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	<span class="token class-name">ClassLoader</span> classLoader <span class="token operator">=</span> <span class="token function">getClassLoader</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token comment">// Use names and ensure unique to protect against duplicates</span>
   <span class="token comment">// 去加载所有FACTORIES_RESOURCE_LOCATION路径下面，也就是 META-INF/spring.factories</span>
	<span class="token class-name">Set</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">></span></span> names <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">LinkedHashSet</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token class-name">SpringFactoriesLoader</span><span class="token punctuation">.</span><span class="token function">loadFactoryNames</span><span class="token punctuation">(</span>type<span class="token punctuation">,</span> classLoader<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">></span></span> instances <span class="token operator">=</span> <span class="token function">createSpringFactoriesInstances</span><span class="token punctuation">(</span>type<span class="token punctuation">,</span> parameterTypes<span class="token punctuation">,</span> classLoader<span class="token punctuation">,</span> args<span class="token punctuation">,</span> names<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token class-name">AnnotationAwareOrderComparator</span><span class="token punctuation">.</span><span class="token function">sort</span><span class="token punctuation">(</span>instances<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token keyword">return</span> instances<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<pre class="line-numbers language-java" data-language="java"><code class="language-java">
<span class="token comment">/**
 * Load the fully qualified class names of factory implementations of the
 * given type from &#123;@value #FACTORIES_RESOURCE_LOCATION&#125;, using the given
 * class loader.
 * &lt;p>As of Spring Framework 5.3, if a particular implementation class name
 * is discovered more than once for the given factory type, duplicates will
 * be ignored.
 * @param factoryType the interface or abstract class representing the factory
 * @param classLoader the ClassLoader to use for loading resources; can be
 * &#123;@code null&#125; to use the default
 * @throws IllegalArgumentException if an error occurs while loading factory names
 * @see #loadFactories
 */</span>
<span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">></span></span> <span class="token function">loadFactoryNames</span><span class="token punctuation">(</span><span class="token class-name">Class</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">></span></span> factoryType<span class="token punctuation">,</span> <span class="token annotation punctuation">@Nullable</span> <span class="token class-name">ClassLoader</span> classLoader<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	<span class="token class-name">ClassLoader</span> classLoaderToUse <span class="token operator">=</span> classLoader<span class="token punctuation">;</span>
	<span class="token keyword">if</span> <span class="token punctuation">(</span>classLoaderToUse <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
		classLoaderToUse <span class="token operator">=</span> <span class="token class-name">SpringFactoriesLoader</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">.</span><span class="token function">getClassLoader</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
	<span class="token class-name">String</span> factoryTypeName <span class="token operator">=</span> factoryType<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token keyword">return</span> <span class="token function">loadSpringFactories</span><span class="token punctuation">(</span>classLoaderToUse<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getOrDefault</span><span class="token punctuation">(</span>factoryTypeName<span class="token punctuation">,</span> <span class="token class-name">Collections</span><span class="token punctuation">.</span><span class="token function">emptyList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
   <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token class-name">Map</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">List</span><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">></span><span class="token punctuation">></span></span> <span class="token function">loadSpringFactories</span><span class="token punctuation">(</span><span class="token class-name">ClassLoader</span> classLoader<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	<span class="token class-name">Map</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">List</span><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">></span><span class="token punctuation">></span></span> result <span class="token operator">=</span> cache<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span>classLoader<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token keyword">if</span> <span class="token punctuation">(</span>result <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
		<span class="token keyword">return</span> result<span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>

	result <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">HashMap</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
           <span class="token comment">// 获取此 resources，作为 AutoConfiguration 的配置</span>
		<span class="token class-name">Enumeration</span><span class="token generics"><span class="token punctuation">&lt;</span>URL<span class="token punctuation">></span></span> urls <span class="token operator">=</span> classLoader<span class="token punctuation">.</span><span class="token function">getResources</span><span class="token punctuation">(</span>FACTORIES_RESOURCE_LOCATION<span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token keyword">while</span> <span class="token punctuation">(</span>urls<span class="token punctuation">.</span><span class="token function">hasMoreElements</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
			<span class="token class-name">URL</span> url <span class="token operator">=</span> urls<span class="token punctuation">.</span><span class="token function">nextElement</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
			<span class="token class-name">UrlResource</span> resource <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">UrlResource</span><span class="token punctuation">(</span>url<span class="token punctuation">)</span><span class="token punctuation">;</span>
			<span class="token class-name">Properties</span> properties <span class="token operator">=</span> <span class="token class-name">PropertiesLoaderUtils</span><span class="token punctuation">.</span><span class="token function">loadProperties</span><span class="token punctuation">(</span>resource<span class="token punctuation">)</span><span class="token punctuation">;</span>
			<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">Map<span class="token punctuation">.</span>Entry</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span><span class="token punctuation">,</span> <span class="token operator">?</span><span class="token punctuation">></span></span> entry <span class="token operator">:</span> properties<span class="token punctuation">.</span><span class="token function">entrySet</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
				<span class="token class-name">String</span> factoryTypeName <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">)</span> entry<span class="token punctuation">.</span><span class="token function">getKey</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">trim</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
				<span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> factoryImplementationNames <span class="token operator">=</span>
						<span class="token class-name">StringUtils</span><span class="token punctuation">.</span><span class="token function">commaDelimitedListToStringArray</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">)</span> entry<span class="token punctuation">.</span><span class="token function">getValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
				<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">String</span> factoryImplementationName <span class="token operator">:</span> factoryImplementationNames<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
					result<span class="token punctuation">.</span><span class="token function">computeIfAbsent</span><span class="token punctuation">(</span>factoryTypeName<span class="token punctuation">,</span> key <span class="token operator">-></span> <span class="token keyword">new</span> <span class="token class-name">ArrayList</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
							<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>factoryImplementationName<span class="token punctuation">.</span><span class="token function">trim</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
				<span class="token punctuation">&#125;</span>
			<span class="token punctuation">&#125;</span>
		<span class="token punctuation">&#125;</span>

		<span class="token comment">// Replace all lists with unmodifiable lists containing unique elements</span>
		result<span class="token punctuation">.</span><span class="token function">replaceAll</span><span class="token punctuation">(</span><span class="token punctuation">(</span>factoryType<span class="token punctuation">,</span> implementations<span class="token punctuation">)</span> <span class="token operator">-></span> implementations<span class="token punctuation">.</span><span class="token function">stream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">distinct</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
				<span class="token punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span><span class="token class-name">Collectors</span><span class="token punctuation">.</span><span class="token function">collectingAndThen</span><span class="token punctuation">(</span><span class="token class-name">Collectors</span><span class="token punctuation">.</span><span class="token function">toList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token class-name">Collections</span><span class="token operator">::</span><span class="token function">unmodifiableList</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		cache<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span>classLoader<span class="token punctuation">,</span> result<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
	<span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">IOException</span> ex<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
		<span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">IllegalArgumentException</span><span class="token punctuation">(</span><span class="token string">"Unable to load factories from location ["</span> <span class="token operator">+</span>
				FACTORIES_RESOURCE_LOCATION <span class="token operator">+</span> <span class="token string">"]"</span><span class="token punctuation">,</span> ex<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
	<span class="token keyword">return</span> result<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>我们可以看下 spring-boot-autoconfigure 的 META-INF/spring.factories</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"># <span class="token class-name">Initializers</span>
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>context<span class="token punctuation">.</span></span>ApplicationContextInitializer</span><span class="token operator">=</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span></span>SharedMetadataReaderFactoryContextInitializer</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>logging<span class="token punctuation">.</span></span>ConditionEvaluationReportLoggingListener</span>

# <span class="token class-name">Application</span> <span class="token class-name">Listeners</span>
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>context<span class="token punctuation">.</span></span>ApplicationListener</span><span class="token operator">=</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span></span>BackgroundPreinitializer</span>

# <span class="token class-name">Environment</span> <span class="token class-name">Post</span> <span class="token class-name">Processors</span>
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>env<span class="token punctuation">.</span></span>EnvironmentPostProcessor</span><span class="token operator">=</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>integration<span class="token punctuation">.</span></span>IntegrationPropertiesEnvironmentPostProcessor</span>

# <span class="token class-name">Auto</span> <span class="token class-name">Configuration</span> <span class="token class-name">Import</span> <span class="token class-name">Listeners</span>
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span></span>AutoConfigurationImportListener</span><span class="token operator">=</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>condition<span class="token punctuation">.</span></span>ConditionEvaluationReportAutoConfigurationImportListener</span>

# <span class="token class-name">Auto</span> <span class="token class-name">Configuration</span> <span class="token class-name">Import</span> <span class="token class-name">Filters</span>
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span></span>AutoConfigurationImportFilter</span><span class="token operator">=</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>condition<span class="token punctuation">.</span></span>OnBeanCondition</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>condition<span class="token punctuation">.</span></span>OnClassCondition</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>condition<span class="token punctuation">.</span></span>OnWebApplicationCondition</span>

# 注意这里，其实就是类似于 dubbo spi 的通过 <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span></span>EnableAutoConfiguration</span>作为 key
# 获取下面所有的 <span class="token class-name">AutoConfiguration</span> 配置类
# <span class="token class-name">Auto</span> <span class="token class-name">Configure</span>
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span></span>EnableAutoConfiguration</span><span class="token operator">=</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>admin<span class="token punctuation">.</span></span>SpringApplicationAdminJmxAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>aop<span class="token punctuation">.</span></span>AopAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>amqp<span class="token punctuation">.</span></span>RabbitAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>batch<span class="token punctuation">.</span></span>BatchAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>cache<span class="token punctuation">.</span></span>CacheAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>cassandra<span class="token punctuation">.</span></span>CassandraAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>context<span class="token punctuation">.</span></span>ConfigurationPropertiesAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>context<span class="token punctuation">.</span></span>LifecycleAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>context<span class="token punctuation">.</span></span>MessageSourceAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>context<span class="token punctuation">.</span></span>PropertyPlaceholderAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>couchbase<span class="token punctuation">.</span></span>CouchbaseAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>dao<span class="token punctuation">.</span></span>PersistenceExceptionTranslationAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>cassandra<span class="token punctuation">.</span></span>CassandraDataAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>cassandra<span class="token punctuation">.</span></span>CassandraReactiveDataAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>cassandra<span class="token punctuation">.</span></span>CassandraReactiveRepositoriesAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>cassandra<span class="token punctuation">.</span></span>CassandraRepositoriesAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>couchbase<span class="token punctuation">.</span></span>CouchbaseDataAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>couchbase<span class="token punctuation">.</span></span>CouchbaseReactiveDataAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>couchbase<span class="token punctuation">.</span></span>CouchbaseReactiveRepositoriesAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>couchbase<span class="token punctuation">.</span></span>CouchbaseRepositoriesAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>elasticsearch<span class="token punctuation">.</span></span>ElasticsearchDataAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>elasticsearch<span class="token punctuation">.</span></span>ElasticsearchRepositoriesAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>elasticsearch<span class="token punctuation">.</span></span>ReactiveElasticsearchRepositoriesAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>elasticsearch<span class="token punctuation">.</span></span>ReactiveElasticsearchRestClientAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>jdbc<span class="token punctuation">.</span></span>JdbcRepositoriesAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>jpa<span class="token punctuation">.</span></span>JpaRepositoriesAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>ldap<span class="token punctuation">.</span></span>LdapRepositoriesAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>mongo<span class="token punctuation">.</span></span>MongoDataAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>mongo<span class="token punctuation">.</span></span>MongoReactiveDataAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>mongo<span class="token punctuation">.</span></span>MongoReactiveRepositoriesAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>mongo<span class="token punctuation">.</span></span>MongoRepositoriesAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>neo4j<span class="token punctuation">.</span></span>Neo4jDataAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>neo4j<span class="token punctuation">.</span></span>Neo4jReactiveDataAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>neo4j<span class="token punctuation">.</span></span>Neo4jReactiveRepositoriesAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>neo4j<span class="token punctuation">.</span></span>Neo4jRepositoriesAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>r2dbc<span class="token punctuation">.</span></span>R2dbcDataAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>r2dbc<span class="token punctuation">.</span></span>R2dbcRepositoriesAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>redis<span class="token punctuation">.</span></span>RedisAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>redis<span class="token punctuation">.</span></span>RedisReactiveAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>redis<span class="token punctuation">.</span></span>RedisRepositoriesAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>rest<span class="token punctuation">.</span></span>RepositoryRestMvcAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>web<span class="token punctuation">.</span></span>SpringDataWebAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>elasticsearch<span class="token punctuation">.</span></span>ElasticsearchRestClientAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>flyway<span class="token punctuation">.</span></span>FlywayAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>freemarker<span class="token punctuation">.</span></span>FreeMarkerAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>groovy<span class="token punctuation">.</span>template<span class="token punctuation">.</span></span>GroovyTemplateAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>gson<span class="token punctuation">.</span></span>GsonAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>h2<span class="token punctuation">.</span></span>H2ConsoleAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>hateoas<span class="token punctuation">.</span></span>HypermediaAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>hazelcast<span class="token punctuation">.</span></span>HazelcastAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>hazelcast<span class="token punctuation">.</span></span>HazelcastJpaDependencyAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>http<span class="token punctuation">.</span></span>HttpMessageConvertersAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>http<span class="token punctuation">.</span>codec<span class="token punctuation">.</span></span>CodecsAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>influx<span class="token punctuation">.</span></span>InfluxDbAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>info<span class="token punctuation">.</span></span>ProjectInfoAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>integration<span class="token punctuation">.</span></span>IntegrationAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>jackson<span class="token punctuation">.</span></span>JacksonAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>jdbc<span class="token punctuation">.</span></span>DataSourceAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>jdbc<span class="token punctuation">.</span></span>JdbcTemplateAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>jdbc<span class="token punctuation">.</span></span>JndiDataSourceAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>jdbc<span class="token punctuation">.</span></span>XADataSourceAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>jdbc<span class="token punctuation">.</span></span>DataSourceTransactionManagerAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>jms<span class="token punctuation">.</span></span>JmsAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>jmx<span class="token punctuation">.</span></span>JmxAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>jms<span class="token punctuation">.</span></span>JndiConnectionFactoryAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>jms<span class="token punctuation">.</span>activemq<span class="token punctuation">.</span></span>ActiveMQAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>jms<span class="token punctuation">.</span>artemis<span class="token punctuation">.</span></span>ArtemisAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>jersey<span class="token punctuation">.</span></span>JerseyAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>jooq<span class="token punctuation">.</span></span>JooqAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>jsonb<span class="token punctuation">.</span></span>JsonbAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>kafka<span class="token punctuation">.</span></span>KafkaAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>availability<span class="token punctuation">.</span></span>ApplicationAvailabilityAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>ldap<span class="token punctuation">.</span>embedded<span class="token punctuation">.</span></span>EmbeddedLdapAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>ldap<span class="token punctuation">.</span></span>LdapAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>liquibase<span class="token punctuation">.</span></span>LiquibaseAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>mail<span class="token punctuation">.</span></span>MailSenderAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>mail<span class="token punctuation">.</span></span>MailSenderValidatorAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>mongo<span class="token punctuation">.</span>embedded<span class="token punctuation">.</span></span>EmbeddedMongoAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>mongo<span class="token punctuation">.</span></span>MongoAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>mongo<span class="token punctuation">.</span></span>MongoReactiveAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>mustache<span class="token punctuation">.</span></span>MustacheAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>neo4j<span class="token punctuation">.</span></span>Neo4jAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>netty<span class="token punctuation">.</span></span>NettyAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>orm<span class="token punctuation">.</span>jpa<span class="token punctuation">.</span></span>HibernateJpaAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>quartz<span class="token punctuation">.</span></span>QuartzAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>r2dbc<span class="token punctuation">.</span></span>R2dbcAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>r2dbc<span class="token punctuation">.</span></span>R2dbcTransactionManagerAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>rsocket<span class="token punctuation">.</span></span>RSocketMessagingAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>rsocket<span class="token punctuation">.</span></span>RSocketRequesterAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>rsocket<span class="token punctuation">.</span></span>RSocketServerAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>rsocket<span class="token punctuation">.</span></span>RSocketStrategiesAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>security<span class="token punctuation">.</span>servlet<span class="token punctuation">.</span></span>SecurityAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>security<span class="token punctuation">.</span>servlet<span class="token punctuation">.</span></span>UserDetailsServiceAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>security<span class="token punctuation">.</span>servlet<span class="token punctuation">.</span></span>SecurityFilterAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>security<span class="token punctuation">.</span>reactive<span class="token punctuation">.</span></span>ReactiveSecurityAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>security<span class="token punctuation">.</span>reactive<span class="token punctuation">.</span></span>ReactiveUserDetailsServiceAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>security<span class="token punctuation">.</span>rsocket<span class="token punctuation">.</span></span>RSocketSecurityAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>security<span class="token punctuation">.</span>saml2<span class="token punctuation">.</span></span>Saml2RelyingPartyAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>sendgrid<span class="token punctuation">.</span></span>SendGridAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>session<span class="token punctuation">.</span></span>SessionAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>security<span class="token punctuation">.</span>oauth2<span class="token punctuation">.</span>client<span class="token punctuation">.</span>servlet<span class="token punctuation">.</span></span>OAuth2ClientAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>security<span class="token punctuation">.</span>oauth2<span class="token punctuation">.</span>client<span class="token punctuation">.</span>reactive<span class="token punctuation">.</span></span>ReactiveOAuth2ClientAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>security<span class="token punctuation">.</span>oauth2<span class="token punctuation">.</span>resource<span class="token punctuation">.</span>servlet<span class="token punctuation">.</span></span>OAuth2ResourceServerAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>security<span class="token punctuation">.</span>oauth2<span class="token punctuation">.</span>resource<span class="token punctuation">.</span>reactive<span class="token punctuation">.</span></span>ReactiveOAuth2ResourceServerAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>solr<span class="token punctuation">.</span></span>SolrAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>sql<span class="token punctuation">.</span>init<span class="token punctuation">.</span></span>SqlInitializationAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>task<span class="token punctuation">.</span></span>TaskExecutionAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>task<span class="token punctuation">.</span></span>TaskSchedulingAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>thymeleaf<span class="token punctuation">.</span></span>ThymeleafAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>transaction<span class="token punctuation">.</span></span>TransactionAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>transaction<span class="token punctuation">.</span>jta<span class="token punctuation">.</span></span>JtaAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>validation<span class="token punctuation">.</span></span>ValidationAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>web<span class="token punctuation">.</span>client<span class="token punctuation">.</span></span>RestTemplateAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>web<span class="token punctuation">.</span>embedded<span class="token punctuation">.</span></span>EmbeddedWebServerFactoryCustomizerAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>web<span class="token punctuation">.</span>reactive<span class="token punctuation">.</span></span>HttpHandlerAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>web<span class="token punctuation">.</span>reactive<span class="token punctuation">.</span></span>ReactiveWebServerFactoryAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>web<span class="token punctuation">.</span>reactive<span class="token punctuation">.</span></span>WebFluxAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>web<span class="token punctuation">.</span>reactive<span class="token punctuation">.</span>error<span class="token punctuation">.</span></span>ErrorWebFluxAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>web<span class="token punctuation">.</span>reactive<span class="token punctuation">.</span>function<span class="token punctuation">.</span>client<span class="token punctuation">.</span></span>ClientHttpConnectorAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>web<span class="token punctuation">.</span>reactive<span class="token punctuation">.</span>function<span class="token punctuation">.</span>client<span class="token punctuation">.</span></span>WebClientAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>web<span class="token punctuation">.</span>servlet<span class="token punctuation">.</span></span>DispatcherServletAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>web<span class="token punctuation">.</span>servlet<span class="token punctuation">.</span></span>ServletWebServerFactoryAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>web<span class="token punctuation">.</span>servlet<span class="token punctuation">.</span>error<span class="token punctuation">.</span></span>ErrorMvcAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>web<span class="token punctuation">.</span>servlet<span class="token punctuation">.</span></span>HttpEncodingAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>web<span class="token punctuation">.</span>servlet<span class="token punctuation">.</span></span>MultipartAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>web<span class="token punctuation">.</span>servlet<span class="token punctuation">.</span></span>WebMvcAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>websocket<span class="token punctuation">.</span>reactive<span class="token punctuation">.</span></span>WebSocketReactiveAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>websocket<span class="token punctuation">.</span>servlet<span class="token punctuation">.</span></span>WebSocketServletAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>websocket<span class="token punctuation">.</span>servlet<span class="token punctuation">.</span></span>WebSocketMessagingAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>webservices<span class="token punctuation">.</span></span>WebServicesAutoConfiguration</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>webservices<span class="token punctuation">.</span>client<span class="token punctuation">.</span></span>WebServiceTemplateAutoConfiguration</span>

# <span class="token class-name">Failure</span> analyzers
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>diagnostics<span class="token punctuation">.</span></span>FailureAnalyzer</span><span class="token operator">=</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>data<span class="token punctuation">.</span>redis<span class="token punctuation">.</span></span>RedisUrlSyntaxFailureAnalyzer</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>diagnostics<span class="token punctuation">.</span>analyzer<span class="token punctuation">.</span></span>NoSuchBeanDefinitionFailureAnalyzer</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>flyway<span class="token punctuation">.</span></span>FlywayMigrationScriptMissingFailureAnalyzer</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>jdbc<span class="token punctuation">.</span></span>DataSourceBeanCreationFailureAnalyzer</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>jdbc<span class="token punctuation">.</span></span>HikariDriverConfigurationFailureAnalyzer</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>r2dbc<span class="token punctuation">.</span></span>ConnectionFactoryBeanCreationFailureAnalyzer</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>session<span class="token punctuation">.</span></span>NonUniqueSessionRepositoryFailureAnalyzer</span>

# <span class="token class-name">Template</span> availability providers
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>template<span class="token punctuation">.</span></span>TemplateAvailabilityProvider</span><span class="token operator">=</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>freemarker<span class="token punctuation">.</span></span>FreeMarkerTemplateAvailabilityProvider</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>mustache<span class="token punctuation">.</span></span>MustacheTemplateAvailabilityProvider</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>groovy<span class="token punctuation">.</span>template<span class="token punctuation">.</span></span>GroovyTemplateAvailabilityProvider</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>thymeleaf<span class="token punctuation">.</span></span>ThymeleafTemplateAvailabilityProvider</span><span class="token punctuation">,</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>web<span class="token punctuation">.</span>servlet<span class="token punctuation">.</span></span>JspTemplateAvailabilityProvider</span>

# <span class="token class-name">DataSource</span> initializer detectors
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>sql<span class="token punctuation">.</span>init<span class="token punctuation">.</span>dependency<span class="token punctuation">.</span></span>DatabaseInitializerDetector</span><span class="token operator">=</span>\
<span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>autoconfigure<span class="token punctuation">.</span>flyway<span class="token punctuation">.</span></span>FlywayMigrationInitializerDatabaseInitializerDetector</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>上面根据 org.springframework.boot.autoconfigure.EnableAutoConfiguration 获取的各个配置类，在通过反射加载就能得到一堆 JavaConfig配置类，然后再根据 ConditionalOnProperty等条件配置加载具体的 bean，大致就是这么个逻辑</p>
]]></content>
      <categories>
        <category>Java</category>
        <category>SpringBoot</category>
      </categories>
      <tags>
        <tag>Java</tag>
        <tag>SpringBoot</tag>
        <tag>Spring</tag>
        <tag>自动装配</tag>
        <tag>AutoConfiguration</tag>
      </tags>
  </entry>
  <entry>
    <title>聊一下 RocketMQ 的 DefaultMQPushConsumer 源码</title>
    <url>/2020/06/26/%E8%81%8A%E4%B8%80%E4%B8%8B-RocketMQ-%E7%9A%84-Consumer/</url>
    <content><![CDATA[<p>首先看下官方的小 demo</p>
<pre class="line-numbers language-Java" data-language="Java"><code class="language-Java">public static void main(String[] args) throws InterruptedException, MQClientException &#123;

        &#x2F;*
         * Instantiate with specified consumer group name.
         * 首先是new 一个对象出来，然后指定 Consumer 的 Group
         * 同一类Consumer的集合，这类Consumer通常消费同一类消息且消费逻辑一致。消费者组使得在消息消费方面，实现负载均衡和容错的目标变得非常容易。要注意的是，消费者组的消费者实例必须订阅完全相同的Topic。RocketMQ 支持两种消息模式：集群消费（Clustering）和广播消费（Broadcasting）。
         *&#x2F;
        DefaultMQPushConsumer consumer &#x3D; new DefaultMQPushConsumer(&quot;please_rename_unique_group_name_4&quot;);

        &#x2F;*
         * Specify name server addresses.
         * &lt;p&#x2F;&gt;
         * 这里可以通知指定环境变量或者设置对象参数的形式指定名字空间服务的地址
         *
         * Alternatively, you may specify name server addresses via exporting environmental variable: NAMESRV_ADDR
         * &lt;pre&gt;
         * &#123;@code
         * consumer.setNamesrvAddr(&quot;name-server1-ip:9876;name-server2-ip:9876&quot;);
         * &#125;
         * &lt;&#x2F;pre&gt;
         *&#x2F;

        &#x2F;*
         * Specify where to start in case the specified consumer group is a brand new one.
         * 指定消费起始点
         *&#x2F;
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);

        &#x2F;*
         * Subscribe one more more topics to consume.
         * 指定订阅的 topic 跟 tag，注意后面的是个表达式，可以以 tag1 || tag2 || tag3 传入
         *&#x2F;
        consumer.subscribe(&quot;TopicTest&quot;, &quot;*&quot;);

        &#x2F;*
         *  Register callback to execute on arrival of messages fetched from brokers.
         *  注册具体获得消息后的处理方法
         *&#x2F;
        consumer.registerMessageListener(new MessageListenerConcurrently() &#123;

            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List&lt;MessageExt&gt; msgs,
                ConsumeConcurrentlyContext context) &#123;
                System.out.printf(&quot;%s Receive New Messages: %s %n&quot;, Thread.currentThread().getName(), msgs);
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            &#125;
        &#125;);

        &#x2F;*
         *  Launch the consumer instance.
         * 启动消费者
         *&#x2F;
        consumer.start();

        System.out.printf(&quot;Consumer Started.%n&quot;);
    &#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>然后就是看看 start 的过程了</p>
<pre class="line-numbers language-Java" data-language="Java"><code class="language-Java">&#x2F;**
     * This method gets internal infrastructure readily to serve. Instances must call this method after configuration.
     *
     * @throws MQClientException if there is any client error.
     *&#x2F;
    @Override
    public void start() throws MQClientException &#123;
        setConsumerGroup(NamespaceUtil.wrapNamespace(this.getNamespace(), this.consumerGroup));
        this.defaultMQPushConsumerImpl.start();
        if (null !&#x3D; traceDispatcher) &#123;
            try &#123;
                traceDispatcher.start(this.getNamesrvAddr(), this.getAccessChannel());
            &#125; catch (MQClientException e) &#123;
                log.warn(&quot;trace dispatcher start failed &quot;, e);
            &#125;
        &#125;
    &#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>具体的逻辑在<code>this.defaultMQPushConsumerImpl.start()</code>，这个 defaultMQPushConsumerImpl 就是</p>
<pre class="line-numbers language-Java" data-language="Java"><code class="language-Java">&#x2F;**
     * Internal implementation. Most of the functions herein are delegated to it.
     *&#x2F;
    protected final transient DefaultMQPushConsumerImpl defaultMQPushConsumerImpl;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<pre class="line-numbers language-Java" data-language="Java"><code class="language-Java">public synchronized void start() throws MQClientException &#123;
        switch (this.serviceState) &#123;
            case CREATE_JUST:
                log.info(&quot;the consumer [&#123;&#125;] start beginning. messageModel&#x3D;&#123;&#125;, isUnitMode&#x3D;&#123;&#125;&quot;, this.defaultMQPushConsumer.getConsumerGroup(),
                    this.defaultMQPushConsumer.getMessageModel(), this.defaultMQPushConsumer.isUnitMode());
                &#x2F;&#x2F; 这里比较巧妙，相当于想设立了个屏障，防止并发启动，不过这里并不是悲观锁，也不算个严格的乐观锁
                this.serviceState &#x3D; ServiceState.START_FAILED;

                this.checkConfig();

                this.copySubscription();

                if (this.defaultMQPushConsumer.getMessageModel() &#x3D;&#x3D; MessageModel.CLUSTERING) &#123;
                    this.defaultMQPushConsumer.changeInstanceNameToPID();
                &#125;

                &#x2F;&#x2F; 这个mQClientFactory，负责管理client（consumer、producer），并提供多中功能接口供各个Service（Rebalance、PullMessage等）调用；大部分逻辑均在这个类中完成
                this.mQClientFactory &#x3D; MQClientManager.getInstance().getOrCreateMQClientInstance(this.defaultMQPushConsumer, this.rpcHook);

                &#x2F;&#x2F; 这个 rebalanceImpl 主要负责决定，当前的consumer应该从哪些Queue中消费消息；
                this.rebalanceImpl.setConsumerGroup(this.defaultMQPushConsumer.getConsumerGroup());
                this.rebalanceImpl.setMessageModel(this.defaultMQPushConsumer.getMessageModel());
                this.rebalanceImpl.setAllocateMessageQueueStrategy(this.defaultMQPushConsumer.getAllocateMessageQueueStrategy());
                this.rebalanceImpl.setmQClientFactory(this.mQClientFactory);

                &#x2F;&#x2F; 长连接，负责从broker处拉取消息，然后利用ConsumeMessageService回调用户的Listener执行消息消费逻辑
                this.pullAPIWrapper &#x3D; new PullAPIWrapper(
                    mQClientFactory,
                    this.defaultMQPushConsumer.getConsumerGroup(), isUnitMode());
                this.pullAPIWrapper.registerFilterMessageHook(filterMessageHookList);

                if (this.defaultMQPushConsumer.getOffsetStore() !&#x3D; null) &#123;
                    this.offsetStore &#x3D; this.defaultMQPushConsumer.getOffsetStore();
                &#125; else &#123;
                    switch (this.defaultMQPushConsumer.getMessageModel()) &#123;
                        case BROADCASTING:
                            this.offsetStore &#x3D; new LocalFileOffsetStore(this.mQClientFactory, this.defaultMQPushConsumer.getConsumerGroup());
                            break;
                        case CLUSTERING:
                            this.offsetStore &#x3D; new RemoteBrokerOffsetStore(this.mQClientFactory, this.defaultMQPushConsumer.getConsumerGroup());
                            break;
                        default:
                            break;
                    &#125;
                    this.defaultMQPushConsumer.setOffsetStore(this.offsetStore);
                &#125;
                &#x2F;&#x2F; offsetStore 维护当前consumer的消费记录（offset）；有两种实现，Local和Rmote，Local存储在本地磁盘上，适用于BROADCASTING广播消费模式；而Remote则将消费进度存储在Broker上，适用于CLUSTERING集群消费模式；
                this.offsetStore.load();

                if (this.getMessageListenerInner() instanceof MessageListenerOrderly) &#123;
                    this.consumeOrderly &#x3D; true;
                    this.consumeMessageService &#x3D;
                        new ConsumeMessageOrderlyService(this, (MessageListenerOrderly) this.getMessageListenerInner());
                &#125; else if (this.getMessageListenerInner() instanceof MessageListenerConcurrently) &#123;
                    this.consumeOrderly &#x3D; false;
                    this.consumeMessageService &#x3D;
                        new ConsumeMessageConcurrentlyService(this, (MessageListenerConcurrently) this.getMessageListenerInner());
                &#125;

                &#x2F;&#x2F; 实现所谓的&quot;Push-被动&quot;消费机制；从Broker拉取的消息后，封装成ConsumeRequest提交给ConsumeMessageSerivce，此service负责回调用户的Listener消费消息；
                this.consumeMessageService.start();

                boolean registerOK &#x3D; mQClientFactory.registerConsumer(this.defaultMQPushConsumer.getConsumerGroup(), this);
                if (!registerOK) &#123;
                    this.serviceState &#x3D; ServiceState.CREATE_JUST;
                    this.consumeMessageService.shutdown();
                    throw new MQClientException(&quot;The consumer group[&quot; + this.defaultMQPushConsumer.getConsumerGroup()
                        + &quot;] has been created before, specify another name please.&quot; + FAQUrl.suggestTodo(FAQUrl.GROUP_NAME_DUPLICATE_URL),
                        null);
                &#125;

                mQClientFactory.start();
                log.info(&quot;the consumer [&#123;&#125;] start OK.&quot;, this.defaultMQPushConsumer.getConsumerGroup());
                this.serviceState &#x3D; ServiceState.RUNNING;
                break;
            case RUNNING:
            case START_FAILED:
            case SHUTDOWN_ALREADY:
                throw new MQClientException(&quot;The PushConsumer service state not OK, maybe started once, &quot;
                    + this.serviceState
                    + FAQUrl.suggestTodo(FAQUrl.CLIENT_SERVICE_NOT_OK),
                    null);
            default:
                break;
        &#125;

        this.updateTopicSubscribeInfoWhenSubscriptionChanged();
        this.mQClientFactory.checkClientInBroker();
        this.mQClientFactory.sendHeartbeatToAllBrokerWithLock();
        this.mQClientFactory.rebalanceImmediately();
    &#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>然后我们往下看主要的目光聚焦<code>mQClientFactory.start()</code></p>
<pre class="line-numbers language-Java" data-language="Java"><code class="language-Java">public void start() throws MQClientException &#123;

        synchronized (this) &#123;
            switch (this.serviceState) &#123;
                case CREATE_JUST:
                    this.serviceState &#x3D; ServiceState.START_FAILED;
                    &#x2F;&#x2F; If not specified,looking address from name server
                    if (null &#x3D;&#x3D; this.clientConfig.getNamesrvAddr()) &#123;
                        this.mQClientAPIImpl.fetchNameServerAddr();
                    &#125;
                    &#x2F;&#x2F; Start request-response channel
                    &#x2F;&#x2F; 这里主要是初始化了个网络客户端
                    this.mQClientAPIImpl.start();
                    &#x2F;&#x2F; Start various schedule tasks
                    &#x2F;&#x2F; 定时任务
                    this.startScheduledTask();
                    &#x2F;&#x2F; Start pull service
                    &#x2F;&#x2F; 这里重点说下
                    this.pullMessageService.start();
                    &#x2F;&#x2F; Start rebalance service
                    this.rebalanceService.start();
                    &#x2F;&#x2F; Start push service
                    this.defaultMQProducer.getDefaultMQProducerImpl().start(false);
                    log.info(&quot;the client factory [&#123;&#125;] start OK&quot;, this.clientId);
                    this.serviceState &#x3D; ServiceState.RUNNING;
                    break;
                case START_FAILED:
                    throw new MQClientException(&quot;The Factory object[&quot; + this.getClientId() + &quot;] has been created before, and failed.&quot;, null);
                default:
                    break;
            &#125;
        &#125;
    &#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>我们来看下这个 pullMessageService，org.apache.rocketmq.client.impl.consumer.PullMessageService，<br><img data-src="https://mystore-1255223546.cos.ap-chengdu.myqcloud.com/uPic/QdeiVv.png"><br>实现了 runnable 接口，<br>然后可以看到 run 方法</p>
<pre class="line-numbers language-Java" data-language="Java"><code class="language-Java">public void run() &#123;
        log.info(this.getServiceName() + &quot; service started&quot;);

        while (!this.isStopped()) &#123;
            try &#123;
                PullRequest pullRequest &#x3D; this.pullRequestQueue.take();
                this.pullMessage(pullRequest);
            &#125; catch (InterruptedException ignored) &#123;
            &#125; catch (Exception e) &#123;
                log.error(&quot;Pull Message Service Run Method exception&quot;, e);
            &#125;
        &#125;

        log.info(this.getServiceName() + &quot; service end&quot;);
    &#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>接着在看 pullMessage 方法</p>
<pre class="line-numbers language-Java" data-language="Java"><code class="language-Java">private void pullMessage(final PullRequest pullRequest) &#123;
        final MQConsumerInner consumer &#x3D; this.mQClientFactory.selectConsumer(pullRequest.getConsumerGroup());
        if (consumer !&#x3D; null) &#123;
            DefaultMQPushConsumerImpl impl &#x3D; (DefaultMQPushConsumerImpl) consumer;
            impl.pullMessage(pullRequest);
        &#125; else &#123;
            log.warn(&quot;No matched consumer for the PullRequest &#123;&#125;, drop it&quot;, pullRequest);
        &#125;
    &#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>实际上调用了这个方法，这个方法很长，我在代码里注释下下每一段的功能</p>
<pre class="line-numbers language-Java" data-language="Java"><code class="language-Java">public void pullMessage(final PullRequest pullRequest) &#123;
        final ProcessQueue processQueue &#x3D; pullRequest.getProcessQueue();
        &#x2F;&#x2F; 这里开始就是检查状态，确定是否往下执行
        if (processQueue.isDropped()) &#123;
            log.info(&quot;the pull request[&#123;&#125;] is dropped.&quot;, pullRequest.toString());
            return;
        &#125;

        pullRequest.getProcessQueue().setLastPullTimestamp(System.currentTimeMillis());

        try &#123;
            this.makeSureStateOK();
        &#125; catch (MQClientException e) &#123;
            log.warn(&quot;pullMessage exception, consumer state not ok&quot;, e);
            this.executePullRequestLater(pullRequest, pullTimeDelayMillsWhenException);
            return;
        &#125;

        if (this.isPause()) &#123;
            log.warn(&quot;consumer was paused, execute pull request later. instanceName&#x3D;&#123;&#125;, group&#x3D;&#123;&#125;&quot;, this.defaultMQPushConsumer.getInstanceName(), this.defaultMQPushConsumer.getConsumerGroup());
            this.executePullRequestLater(pullRequest, PULL_TIME_DELAY_MILLS_WHEN_SUSPEND);
            return;
        &#125;

        &#x2F;&#x2F; 这块其实是个类似于限流的功能块，对消息数量和消息大小做限制
        long cachedMessageCount &#x3D; processQueue.getMsgCount().get();
        long cachedMessageSizeInMiB &#x3D; processQueue.getMsgSize().get() &#x2F; (1024 * 1024);

        if (cachedMessageCount &gt; this.defaultMQPushConsumer.getPullThresholdForQueue()) &#123;
            this.executePullRequestLater(pullRequest, PULL_TIME_DELAY_MILLS_WHEN_FLOW_CONTROL);
            if ((queueFlowControlTimes++ % 1000) &#x3D;&#x3D; 0) &#123;
                log.warn(
                    &quot;the cached message count exceeds the threshold &#123;&#125;, so do flow control, minOffset&#x3D;&#123;&#125;, maxOffset&#x3D;&#123;&#125;, count&#x3D;&#123;&#125;, size&#x3D;&#123;&#125; MiB, pullRequest&#x3D;&#123;&#125;, flowControlTimes&#x3D;&#123;&#125;&quot;,
                    this.defaultMQPushConsumer.getPullThresholdForQueue(), processQueue.getMsgTreeMap().firstKey(), processQueue.getMsgTreeMap().lastKey(), cachedMessageCount, cachedMessageSizeInMiB, pullRequest, queueFlowControlTimes);
            &#125;
            return;
        &#125;

        if (cachedMessageSizeInMiB &gt; this.defaultMQPushConsumer.getPullThresholdSizeForQueue()) &#123;
            this.executePullRequestLater(pullRequest, PULL_TIME_DELAY_MILLS_WHEN_FLOW_CONTROL);
            if ((queueFlowControlTimes++ % 1000) &#x3D;&#x3D; 0) &#123;
                log.warn(
                    &quot;the cached message size exceeds the threshold &#123;&#125; MiB, so do flow control, minOffset&#x3D;&#123;&#125;, maxOffset&#x3D;&#123;&#125;, count&#x3D;&#123;&#125;, size&#x3D;&#123;&#125; MiB, pullRequest&#x3D;&#123;&#125;, flowControlTimes&#x3D;&#123;&#125;&quot;,
                    this.defaultMQPushConsumer.getPullThresholdSizeForQueue(), processQueue.getMsgTreeMap().firstKey(), processQueue.getMsgTreeMap().lastKey(), cachedMessageCount, cachedMessageSizeInMiB, pullRequest, queueFlowControlTimes);
            &#125;
            return;
        &#125;

        &#x2F;&#x2F; 若不是顺序消费（即DefaultMQPushConsumerImpl.consumeOrderly等于false），则检查ProcessQueue对象的msgTreeMap:TreeMap&lt;Long,MessageExt&gt;变量的第一个key值与最后一个key值之间的差额，该key值表示查询的队列偏移量queueoffset；若差额大于阈值（由DefaultMQPushConsumer. consumeConcurrentlyMaxSpan指定，默认是2000），则调用PullMessageService.executePullRequestLater方法，在50毫秒之后重新将该PullRequest请求放入PullMessageService.pullRequestQueue队列中；并跳出该方法；这里的意思主要就是消息有堆积了，等会再来拉取
        if (!this.consumeOrderly) &#123;
            if (processQueue.getMaxSpan() &gt; this.defaultMQPushConsumer.getConsumeConcurrentlyMaxSpan()) &#123;
                this.executePullRequestLater(pullRequest, PULL_TIME_DELAY_MILLS_WHEN_FLOW_CONTROL);
                if ((queueMaxSpanFlowControlTimes++ % 1000) &#x3D;&#x3D; 0) &#123;
                    log.warn(
                        &quot;the queue&#39;s messages, span too long, so do flow control, minOffset&#x3D;&#123;&#125;, maxOffset&#x3D;&#123;&#125;, maxSpan&#x3D;&#123;&#125;, pullRequest&#x3D;&#123;&#125;, flowControlTimes&#x3D;&#123;&#125;&quot;,
                        processQueue.getMsgTreeMap().firstKey(), processQueue.getMsgTreeMap().lastKey(), processQueue.getMaxSpan(),
                        pullRequest, queueMaxSpanFlowControlTimes);
                &#125;
                return;
            &#125;
        &#125; else &#123;
            if (processQueue.isLocked()) &#123;
                if (!pullRequest.isLockedFirst()) &#123;
                    final long offset &#x3D; this.rebalanceImpl.computePullFromWhere(pullRequest.getMessageQueue());
                    boolean brokerBusy &#x3D; offset &lt; pullRequest.getNextOffset();
                    log.info(&quot;the first time to pull message, so fix offset from broker. pullRequest: &#123;&#125; NewOffset: &#123;&#125; brokerBusy: &#123;&#125;&quot;,
                        pullRequest, offset, brokerBusy);
                    if (brokerBusy) &#123;
                        log.info(&quot;[NOTIFYME]the first time to pull message, but pull request offset larger than broker consume offset. pullRequest: &#123;&#125; NewOffset: &#123;&#125;&quot;,
                            pullRequest, offset);
                    &#125;

                    pullRequest.setLockedFirst(true);
                    pullRequest.setNextOffset(offset);
                &#125;
            &#125; else &#123;
                this.executePullRequestLater(pullRequest, pullTimeDelayMillsWhenException);
                log.info(&quot;pull message later because not locked in broker, &#123;&#125;&quot;, pullRequest);
                return;
            &#125;
        &#125;

        &#x2F;&#x2F; 以PullRequest.messageQueue对象的topic值为参数从RebalanceImpl.subscriptionInner: ConcurrentHashMap, SubscriptionData&gt;中获取对应的SubscriptionData对象，若该对象为null，考虑到并发的关系，调用executePullRequestLater方法，稍后重试；并跳出该方法；
        final SubscriptionData subscriptionData &#x3D; this.rebalanceImpl.getSubscriptionInner().get(pullRequest.getMessageQueue().getTopic());
        if (null &#x3D;&#x3D; subscriptionData) &#123;
            this.executePullRequestLater(pullRequest, pullTimeDelayMillsWhenException);
            log.warn(&quot;find the consumer&#39;s subscription failed, &#123;&#125;&quot;, pullRequest);
            return;
        &#125;

        final long beginTimestamp &#x3D; System.currentTimeMillis();

        &#x2F;&#x2F; 异步拉取回调，先不讨论细节
        PullCallback pullCallback &#x3D; new PullCallback() &#123;
            @Override
            public void onSuccess(PullResult pullResult) &#123;
                if (pullResult !&#x3D; null) &#123;
                    pullResult &#x3D; DefaultMQPushConsumerImpl.this.pullAPIWrapper.processPullResult(pullRequest.getMessageQueue(), pullResult,
                        subscriptionData);

                    switch (pullResult.getPullStatus()) &#123;
                        case FOUND:
                            long prevRequestOffset &#x3D; pullRequest.getNextOffset();
                            pullRequest.setNextOffset(pullResult.getNextBeginOffset());
                            long pullRT &#x3D; System.currentTimeMillis() - beginTimestamp;
                            DefaultMQPushConsumerImpl.this.getConsumerStatsManager().incPullRT(pullRequest.getConsumerGroup(),
                                pullRequest.getMessageQueue().getTopic(), pullRT);

                            long firstMsgOffset &#x3D; Long.MAX_VALUE;
                            if (pullResult.getMsgFoundList() &#x3D;&#x3D; null || pullResult.getMsgFoundList().isEmpty()) &#123;
                                DefaultMQPushConsumerImpl.this.executePullRequestImmediately(pullRequest);
                            &#125; else &#123;
                                firstMsgOffset &#x3D; pullResult.getMsgFoundList().get(0).getQueueOffset();

                                DefaultMQPushConsumerImpl.this.getConsumerStatsManager().incPullTPS(pullRequest.getConsumerGroup(),
                                    pullRequest.getMessageQueue().getTopic(), pullResult.getMsgFoundList().size());

                                boolean dispatchToConsume &#x3D; processQueue.putMessage(pullResult.getMsgFoundList());
                                DefaultMQPushConsumerImpl.this.consumeMessageService.submitConsumeRequest(
                                    pullResult.getMsgFoundList(),
                                    processQueue,
                                    pullRequest.getMessageQueue(),
                                    dispatchToConsume);

                                if (DefaultMQPushConsumerImpl.this.defaultMQPushConsumer.getPullInterval() &gt; 0) &#123;
                                    DefaultMQPushConsumerImpl.this.executePullRequestLater(pullRequest,
                                        DefaultMQPushConsumerImpl.this.defaultMQPushConsumer.getPullInterval());
                                &#125; else &#123;
                                    DefaultMQPushConsumerImpl.this.executePullRequestImmediately(pullRequest);
                                &#125;
                            &#125;

                            if (pullResult.getNextBeginOffset() &lt; prevRequestOffset
                                || firstMsgOffset &lt; prevRequestOffset) &#123;
                                log.warn(
                                    &quot;[BUG] pull message result maybe data wrong, nextBeginOffset: &#123;&#125; firstMsgOffset: &#123;&#125; prevRequestOffset: &#123;&#125;&quot;,
                                    pullResult.getNextBeginOffset(),
                                    firstMsgOffset,
                                    prevRequestOffset);
                            &#125;

                            break;
                        case NO_NEW_MSG:
                            pullRequest.setNextOffset(pullResult.getNextBeginOffset());

                            DefaultMQPushConsumerImpl.this.correctTagsOffset(pullRequest);

                            DefaultMQPushConsumerImpl.this.executePullRequestImmediately(pullRequest);
                            break;
                        case NO_MATCHED_MSG:
                            pullRequest.setNextOffset(pullResult.getNextBeginOffset());

                            DefaultMQPushConsumerImpl.this.correctTagsOffset(pullRequest);

                            DefaultMQPushConsumerImpl.this.executePullRequestImmediately(pullRequest);
                            break;
                        case OFFSET_ILLEGAL:
                            log.warn(&quot;the pull request offset illegal, &#123;&#125; &#123;&#125;&quot;,
                                pullRequest.toString(), pullResult.toString());
                            pullRequest.setNextOffset(pullResult.getNextBeginOffset());

                            pullRequest.getProcessQueue().setDropped(true);
                            DefaultMQPushConsumerImpl.this.executeTaskLater(new Runnable() &#123;

                                @Override
                                public void run() &#123;
                                    try &#123;
                                        DefaultMQPushConsumerImpl.this.offsetStore.updateOffset(pullRequest.getMessageQueue(),
                                            pullRequest.getNextOffset(), false);

                                        DefaultMQPushConsumerImpl.this.offsetStore.persist(pullRequest.getMessageQueue());

                                        DefaultMQPushConsumerImpl.this.rebalanceImpl.removeProcessQueue(pullRequest.getMessageQueue());

                                        log.warn(&quot;fix the pull request offset, &#123;&#125;&quot;, pullRequest);
                                    &#125; catch (Throwable e) &#123;
                                        log.error(&quot;executeTaskLater Exception&quot;, e);
                                    &#125;
                                &#125;
                            &#125;, 10000);
                            break;
                        default:
                            break;
                    &#125;
                &#125;
            &#125;

            @Override
            public void onException(Throwable e) &#123;
                if (!pullRequest.getMessageQueue().getTopic().startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX)) &#123;
                    log.warn(&quot;execute the pull request exception&quot;, e);
                &#125;

                DefaultMQPushConsumerImpl.this.executePullRequestLater(pullRequest, pullTimeDelayMillsWhenException);
            &#125;
        &#125;;
        &#x2F;&#x2F; 如果为集群模式，即可置commitOffsetEnable为 true
        boolean commitOffsetEnable &#x3D; false;
        long commitOffsetValue &#x3D; 0L;
        if (MessageModel.CLUSTERING &#x3D;&#x3D; this.defaultMQPushConsumer.getMessageModel()) &#123;
            commitOffsetValue &#x3D; this.offsetStore.readOffset(pullRequest.getMessageQueue(), ReadOffsetType.READ_FROM_MEMORY);
            if (commitOffsetValue &gt; 0) &#123;
                commitOffsetEnable &#x3D; true;
            &#125;
        &#125;

        &#x2F;&#x2F; 将上面获得的commitOffsetEnable更新到订阅关系里
        String subExpression &#x3D; null;
        boolean classFilter &#x3D; false;
        SubscriptionData sd &#x3D; this.rebalanceImpl.getSubscriptionInner().get(pullRequest.getMessageQueue().getTopic());
        if (sd !&#x3D; null) &#123;
            if (this.defaultMQPushConsumer.isPostSubscriptionWhenPull() &amp;&amp; !sd.isClassFilterMode()) &#123;
                subExpression &#x3D; sd.getSubString();
            &#125;

            classFilter &#x3D; sd.isClassFilterMode();
        &#125;

        &#x2F;&#x2F; 组成 sysFlag
        int sysFlag &#x3D; PullSysFlag.buildSysFlag(
            commitOffsetEnable, &#x2F;&#x2F; commitOffset
            true, &#x2F;&#x2F; suspend
            subExpression !&#x3D; null, &#x2F;&#x2F; subscription
            classFilter &#x2F;&#x2F; class filter
        );
        &#x2F;&#x2F; 调用真正的拉取消息接口
        try &#123;
            this.pullAPIWrapper.pullKernelImpl(
                pullRequest.getMessageQueue(),
                subExpression,
                subscriptionData.getExpressionType(),
                subscriptionData.getSubVersion(),
                pullRequest.getNextOffset(),
                this.defaultMQPushConsumer.getPullBatchSize(),
                sysFlag,
                commitOffsetValue,
                BROKER_SUSPEND_MAX_TIME_MILLIS,
                CONSUMER_TIMEOUT_MILLIS_WHEN_SUSPEND,
                CommunicationMode.ASYNC,
                pullCallback
            );
        &#125; catch (Exception e) &#123;
            log.error(&quot;pullKernelImpl exception&quot;, e);
            this.executePullRequestLater(pullRequest, pullTimeDelayMillsWhenException);
        &#125;
    &#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>以下就是拉取消息的底层 api，不够不是特别复杂，主要是在找 broker，和设置请求参数</p>
<pre class="line-numbers language-Java" data-language="Java"><code class="language-Java">public PullResult pullKernelImpl(
    final MessageQueue mq,
    final String subExpression,
    final String expressionType,
    final long subVersion,
    final long offset,
    final int maxNums,
    final int sysFlag,
    final long commitOffset,
    final long brokerSuspendMaxTimeMillis,
    final long timeoutMillis,
    final CommunicationMode communicationMode,
    final PullCallback pullCallback
) throws MQClientException, RemotingException, MQBrokerException, InterruptedException &#123;
    FindBrokerResult findBrokerResult &#x3D;
        this.mQClientFactory.findBrokerAddressInSubscribe(mq.getBrokerName(),
            this.recalculatePullFromWhichNode(mq), false);
    if (null &#x3D;&#x3D; findBrokerResult) &#123;
        this.mQClientFactory.updateTopicRouteInfoFromNameServer(mq.getTopic());
        findBrokerResult &#x3D;
            this.mQClientFactory.findBrokerAddressInSubscribe(mq.getBrokerName(),
                this.recalculatePullFromWhichNode(mq), false);
    &#125;

    if (findBrokerResult !&#x3D; null) &#123;
        &#123;
            &#x2F;&#x2F; check version
            if (!ExpressionType.isTagType(expressionType)
                &amp;&amp; findBrokerResult.getBrokerVersion() &lt; MQVersion.Version.V4_1_0_SNAPSHOT.ordinal()) &#123;
                throw new MQClientException(&quot;The broker[&quot; + mq.getBrokerName() + &quot;, &quot;
                    + findBrokerResult.getBrokerVersion() + &quot;] does not upgrade to support for filter message by &quot; + expressionType, null);
            &#125;
        &#125;
        int sysFlagInner &#x3D; sysFlag;

        if (findBrokerResult.isSlave()) &#123;
            sysFlagInner &#x3D; PullSysFlag.clearCommitOffsetFlag(sysFlagInner);
        &#125;

        PullMessageRequestHeader requestHeader &#x3D; new PullMessageRequestHeader();
        requestHeader.setConsumerGroup(this.consumerGroup);
        requestHeader.setTopic(mq.getTopic());
        requestHeader.setQueueId(mq.getQueueId());
        requestHeader.setQueueOffset(offset);
        requestHeader.setMaxMsgNums(maxNums);
        requestHeader.setSysFlag(sysFlagInner);
        requestHeader.setCommitOffset(commitOffset);
        requestHeader.setSuspendTimeoutMillis(brokerSuspendMaxTimeMillis);
        requestHeader.setSubscription(subExpression);
        requestHeader.setSubVersion(subVersion);
        requestHeader.setExpressionType(expressionType);

        String brokerAddr &#x3D; findBrokerResult.getBrokerAddr();
        if (PullSysFlag.hasClassFilterFlag(sysFlagInner)) &#123;
            brokerAddr &#x3D; computPullFromWhichFilterServer(mq.getTopic(), brokerAddr);
        &#125;

        PullResult pullResult &#x3D; this.mQClientFactory.getMQClientAPIImpl().pullMessage(
            brokerAddr,
            requestHeader,
            timeoutMillis,
            communicationMode,
            pullCallback);

        return pullResult;
    &#125;

    throw new MQClientException(&quot;The broker[&quot; + mq.getBrokerName() + &quot;] not exist&quot;, null);
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>再看下一步的</p>
<pre class="line-numbers language-Java" data-language="Java"><code class="language-Java">public PullResult pullMessage(
    final String addr,
    final PullMessageRequestHeader requestHeader,
    final long timeoutMillis,
    final CommunicationMode communicationMode,
    final PullCallback pullCallback
) throws RemotingException, MQBrokerException, InterruptedException &#123;
    RemotingCommand request &#x3D; RemotingCommand.createRequestCommand(RequestCode.PULL_MESSAGE, requestHeader);

    switch (communicationMode) &#123;
        case ONEWAY:
            assert false;
            return null;
        case ASYNC:
            this.pullMessageAsync(addr, request, timeoutMillis, pullCallback);
            return null;
        case SYNC:
            return this.pullMessageSync(addr, request, timeoutMillis);
        default:
            assert false;
            break;
    &#125;

    return null;
&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>通过 communicationMode 判断是同步拉取还是异步拉取，异步就调用</p>
<pre class="line-numbers language-Java" data-language="Java"><code class="language-Java">private void pullMessageAsync(
        final String addr,
        final RemotingCommand request,
        final long timeoutMillis,
        final PullCallback pullCallback
    ) throws RemotingException, InterruptedException &#123;
        this.remotingClient.invokeAsync(addr, request, timeoutMillis, new InvokeCallback() &#123;
            @Override
            public void operationComplete(ResponseFuture responseFuture) &#123;
                异步
                RemotingCommand response &#x3D; responseFuture.getResponseCommand();
                if (response !&#x3D; null) &#123;
                    try &#123;
                        PullResult pullResult &#x3D; MQClientAPIImpl.this.processPullResponse(response);
                        assert pullResult !&#x3D; null;
                        pullCallback.onSuccess(pullResult);
                    &#125; catch (Exception e) &#123;
                        pullCallback.onException(e);
                    &#125;
                &#125; else &#123;
                    if (!responseFuture.isSendRequestOK()) &#123;
                        pullCallback.onException(new MQClientException(&quot;send request failed to &quot; + addr + &quot;. Request: &quot; + request, responseFuture.getCause()));
                    &#125; else if (responseFuture.isTimeout()) &#123;
                        pullCallback.onException(new MQClientException(&quot;wait response from &quot; + addr + &quot; timeout :&quot; + responseFuture.getTimeoutMillis() + &quot;ms&quot; + &quot;. Request: &quot; + request,
                            responseFuture.getCause()));
                    &#125; else &#123;
                        pullCallback.onException(new MQClientException(&quot;unknown reason. addr: &quot; + addr + &quot;, timeoutMillis: &quot; + timeoutMillis + &quot;. Request: &quot; + request, responseFuture.getCause()));
                    &#125;
                &#125;
            &#125;
        &#125;);
    &#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>并且会调用前面 pullCallback 的onSuccess和onException方法，同步的就是调用</p>
<pre class="line-numbers language-Java" data-language="Java"><code class="language-Java">private PullResult pullMessageSync(
        final String addr,
        final RemotingCommand request,
        final long timeoutMillis
    ) throws RemotingException, InterruptedException, MQBrokerException &#123;
        RemotingCommand response &#x3D; this.remotingClient.invokeSync(addr, request, timeoutMillis);
        assert response !&#x3D; null;
        return this.processPullResponse(response);
    &#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>然后就是这个 remotingClient 的 invokeAsync 跟 invokeSync 方法</p>
<pre class="line-numbers language-Java" data-language="Java"><code class="language-Java">@Override
    public void invokeAsync(String addr, RemotingCommand request, long timeoutMillis, InvokeCallback invokeCallback)
        throws InterruptedException, RemotingConnectException, RemotingTooMuchRequestException, RemotingTimeoutException,
        RemotingSendRequestException &#123;
        long beginStartTime &#x3D; System.currentTimeMillis();
        final Channel channel &#x3D; this.getAndCreateChannel(addr);
        if (channel !&#x3D; null &amp;&amp; channel.isActive()) &#123;
            try &#123;
                doBeforeRpcHooks(addr, request);
                long costTime &#x3D; System.currentTimeMillis() - beginStartTime;
                if (timeoutMillis &lt; costTime) &#123;
                    throw new RemotingTooMuchRequestException(&quot;invokeAsync call timeout&quot;);
                &#125;
                this.invokeAsyncImpl(channel, request, timeoutMillis - costTime, invokeCallback);
            &#125; catch (RemotingSendRequestException e) &#123;
                log.warn(&quot;invokeAsync: send request exception, so close the channel[&#123;&#125;]&quot;, addr);
                this.closeChannel(addr, channel);
                throw e;
            &#125;
        &#125; else &#123;
            this.closeChannel(addr, channel);
            throw new RemotingConnectException(addr);
        &#125;
    &#125;
@Override
    public RemotingCommand invokeSync(String addr, final RemotingCommand request, long timeoutMillis)
        throws InterruptedException, RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException &#123;
        long beginStartTime &#x3D; System.currentTimeMillis();
        final Channel channel &#x3D; this.getAndCreateChannel(addr);
        if (channel !&#x3D; null &amp;&amp; channel.isActive()) &#123;
            try &#123;
                doBeforeRpcHooks(addr, request);
                long costTime &#x3D; System.currentTimeMillis() - beginStartTime;
                if (timeoutMillis &lt; costTime) &#123;
                    throw new RemotingTimeoutException(&quot;invokeSync call timeout&quot;);
                &#125;
                RemotingCommand response &#x3D; this.invokeSyncImpl(channel, request, timeoutMillis - costTime);
                doAfterRpcHooks(RemotingHelper.parseChannelRemoteAddr(channel), request, response);
                return response;
            &#125; catch (RemotingSendRequestException e) &#123;
                log.warn(&quot;invokeSync: send request exception, so close the channel[&#123;&#125;]&quot;, addr);
                this.closeChannel(addr, channel);
                throw e;
            &#125; catch (RemotingTimeoutException e) &#123;
                if (nettyClientConfig.isClientCloseSocketIfTimeout()) &#123;
                    this.closeChannel(addr, channel);
                    log.warn(&quot;invokeSync: close socket because of timeout, &#123;&#125;ms, &#123;&#125;&quot;, timeoutMillis, addr);
                &#125;
                log.warn(&quot;invokeSync: wait response timeout exception, the channel[&#123;&#125;]&quot;, addr);
                throw e;
            &#125;
        &#125; else &#123;
            this.closeChannel(addr, channel);
            throw new RemotingConnectException(addr);
        &#125;
    &#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>再往下看</p>
<pre class="line-numbers language-Java" data-language="Java"><code class="language-Java">public RemotingCommand invokeSyncImpl(final Channel channel, final RemotingCommand request,
        final long timeoutMillis)
        throws InterruptedException, RemotingSendRequestException, RemotingTimeoutException &#123;
        final int opaque &#x3D; request.getOpaque();

        try &#123;
            同步跟异步都是会把结果用ResponseFuture抱起来
            final ResponseFuture responseFuture &#x3D; new ResponseFuture(channel, opaque, timeoutMillis, null, null);
            this.responseTable.put(opaque, responseFuture);
            final SocketAddress addr &#x3D; channel.remoteAddress();
            channel.writeAndFlush(request).addListener(new ChannelFutureListener() &#123;
                @Override
                public void operationComplete(ChannelFuture f) throws Exception &#123;
                    if (f.isSuccess()) &#123;
                        responseFuture.setSendRequestOK(true);
                        return;
                    &#125; else &#123;
                        responseFuture.setSendRequestOK(false);
                    &#125;

                    responseTable.remove(opaque);
                    responseFuture.setCause(f.cause());
                    responseFuture.putResponse(null);
                    log.warn(&quot;send a request command to channel &lt;&quot; + addr + &quot;&gt; failed.&quot;);
                &#125;
            &#125;);
            &#x2F;&#x2F; 区别是同步的是在这等待
            RemotingCommand responseCommand &#x3D; responseFuture.waitResponse(timeoutMillis);
            if (null &#x3D;&#x3D; responseCommand) &#123;
                if (responseFuture.isSendRequestOK()) &#123;
                    throw new RemotingTimeoutException(RemotingHelper.parseSocketAddressAddr(addr), timeoutMillis,
                        responseFuture.getCause());
                &#125; else &#123;
                    throw new RemotingSendRequestException(RemotingHelper.parseSocketAddressAddr(addr), responseFuture.getCause());
                &#125;
            &#125;

            return responseCommand;
        &#125; finally &#123;
            this.responseTable.remove(opaque);
        &#125;
    &#125;

    public void invokeAsyncImpl(final Channel channel, final RemotingCommand request, final long timeoutMillis,
        final InvokeCallback invokeCallback)
        throws InterruptedException, RemotingTooMuchRequestException, RemotingTimeoutException, RemotingSendRequestException &#123;
        long beginStartTime &#x3D; System.currentTimeMillis();
        final int opaque &#x3D; request.getOpaque();
        boolean acquired &#x3D; this.semaphoreAsync.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS);
        if (acquired) &#123;
            final SemaphoreReleaseOnlyOnce once &#x3D; new SemaphoreReleaseOnlyOnce(this.semaphoreAsync);
            long costTime &#x3D; System.currentTimeMillis() - beginStartTime;
            if (timeoutMillis &lt; costTime) &#123;
                once.release();
                throw new RemotingTimeoutException(&quot;invokeAsyncImpl call timeout&quot;);
            &#125;

            final ResponseFuture responseFuture &#x3D; new ResponseFuture(channel, opaque, timeoutMillis - costTime, invokeCallback, once);
            this.responseTable.put(opaque, responseFuture);
            try &#123;
                channel.writeAndFlush(request).addListener(new ChannelFutureListener() &#123;
                    @Override
                    public void operationComplete(ChannelFuture f) throws Exception &#123;
                        if (f.isSuccess()) &#123;
                            responseFuture.setSendRequestOK(true);
                            return;
                        &#125;
                        requestFail(opaque);
                        log.warn(&quot;send a request command to channel &lt;&#123;&#125;&gt; failed.&quot;, RemotingHelper.parseChannelRemoteAddr(channel));
                    &#125;
                &#125;);
            &#125; catch (Exception e) &#123;
                responseFuture.release();
                log.warn(&quot;send a request command to channel &lt;&quot; + RemotingHelper.parseChannelRemoteAddr(channel) + &quot;&gt; Exception&quot;, e);
                throw new RemotingSendRequestException(RemotingHelper.parseChannelRemoteAddr(channel), e);
            &#125;
        &#125; else &#123;
            if (timeoutMillis &lt;&#x3D; 0) &#123;
                throw new RemotingTooMuchRequestException(&quot;invokeAsyncImpl invoke too fast&quot;);
            &#125; else &#123;
                String info &#x3D;
                    String.format(&quot;invokeAsyncImpl tryAcquire semaphore timeout, %dms, waiting thread nums: %d semaphoreAsyncValue: %d&quot;,
                        timeoutMillis,
                        this.semaphoreAsync.getQueueLength(),
                        this.semaphoreAsync.availablePermits()
                    );
                log.warn(info);
                throw new RemotingTimeoutException(info);
            &#125;
        &#125;
    &#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



]]></content>
      <categories>
        <category>MQ</category>
        <category>RocketMQ</category>
        <category>消息队列</category>
        <category>RocketMQ</category>
        <category>中间件</category>
        <category>RocketMQ</category>
      </categories>
      <tags>
        <tag>MQ</tag>
        <tag>消息队列</tag>
        <tag>RocketMQ</tag>
        <tag>削峰填谷</tag>
        <tag>中间件</tag>
        <tag>源码解析</tag>
        <tag>DefaultMQPushConsumer</tag>
      </tags>
  </entry>
  <entry>
    <title>聊聊 Java 自带的那些*逆天*工具</title>
    <url>/2020/08/02/%E8%81%8A%E8%81%8A-Java-%E8%87%AA%E5%B8%A6%E7%9A%84%E9%82%A3%E4%BA%9B%E9%80%86%E5%A4%A9%E5%B7%A5%E5%85%B7/</url>
    <content><![CDATA[<p>原谅我的标题党，其实这些工具的确很厉害，之前其实介绍过一点相关的，是从我一次问题排查的过程中用到的，但是最近又有碰到一次排查问题，发现其实用 idea 直接 <code>dump thread</code> 是不现实的，毕竟服务器环境的没法这么操作，那就得用 Java 的那些工具了</p>
<h3 id="jstack-amp-jps"><a href="#jstack-amp-jps" class="headerlink" title="jstack &amp; jps"></a>jstack &amp; jps</h3><p>譬如 <code>jstack</code>，这个命令其实不能更简单了<br>看看 help 信息<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/1eYvcu.png"><br>用<code>-l</code>参数可以打出锁的额外信息，然后后面的 pid 就是进程 id 咯，机智的小伙伴会问了（就你这个小白才问这么蠢的问题🤦‍♂️），怎么看 Java 应用的进程呢<br>那就是 <code>jps</code> 了，命令也很简单，一般直接用 <code>jps</code>命令就好了，不过也可以 help 看一下<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/DqWZe1.png"><br>稍微解释下，-q是只显示进程 id，-m是输出给main 方法的参数，比如我在配置中加给参数<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/4A0pqD.png"><br>然后用 <code>jps -m</code>查看<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/LlGPfU.png"><br><code>-v</code>加上小 v 的话就是打印 jvm 参数<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/3UTgsd.png"><br>还是有点东西，然后就继续介绍 jstack 了，然后我们看看 jstack 出来是啥，为了加点内容我加了个死锁</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">SpringApplication</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">ThreadDumpDemoApplication</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">,</span> args<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">ReentrantLock</span> lock1 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ReentrantLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">ReentrantLock</span> lock2 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ReentrantLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Thread</span> t1 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Thread</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token annotation punctuation">@Override</span>
            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                    lock1<span class="token punctuation">.</span><span class="token function">lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>SECONDS<span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    lock2<span class="token punctuation">.</span><span class="token function">lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">;</span>
        <span class="token class-name">Thread</span> t2 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Thread</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token annotation punctuation">@Override</span>
            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
                    lock2<span class="token punctuation">.</span><span class="token function">lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span>SECONDS<span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    lock1<span class="token punctuation">.</span><span class="token function">lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                    e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">&#125;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">;</span>
        t1<span class="token punctuation">.</span><span class="token function">setName</span><span class="token punctuation">(</span><span class="token string">"mythread1"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        t2<span class="token punctuation">.</span><span class="token function">setName</span><span class="token punctuation">(</span><span class="token string">"mythread2"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        t1<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        t2<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">10000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>然后看看出来时怎么样的</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token number">2020</span><span class="token operator">-</span><span class="token number">08</span><span class="token operator">-</span><span class="token number">02</span> <span class="token number">21</span><span class="token operator">:</span><span class="token number">50</span><span class="token operator">:</span><span class="token number">32</span>
<span class="token class-name">Full</span> thread dump <span class="token class-name">Java</span> <span class="token class-name">HotSpot</span><span class="token punctuation">(</span>TM<span class="token punctuation">)</span> <span class="token number">64</span><span class="token operator">-</span><span class="token class-name">Bit</span> <span class="token class-name">Server</span> VM <span class="token punctuation">(</span><span class="token number">25.201</span><span class="token operator">-</span>b09 mixed mode<span class="token punctuation">)</span><span class="token operator">:</span>

<span class="token string">"DestroyJavaVM"</span> #<span class="token number">147</span> prio<span class="token operator">=</span><span class="token number">5</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9dd807000</span> nid<span class="token operator">=</span><span class="token number">0x2603</span> waiting on condition <span class="token punctuation">[</span><span class="token number">0x0000000000000000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> RUNNABLE

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token class-name">None</span>

<span class="token string">"mythread2"</span> #<span class="token number">140</span> prio<span class="token operator">=</span><span class="token number">5</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9dd877000</span> nid<span class="token operator">=</span><span class="token number">0x9903</span> waiting on condition <span class="token punctuation">[</span><span class="token number">0x0000700006fb9000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> WAITING <span class="token punctuation">(</span>parking<span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>misc<span class="token punctuation">.</span></span>Unsafe</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">Native</span> <span class="token class-name">Method</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> parking <span class="token keyword">to</span> <span class="token namespace">wait</span> <span class="token keyword">for</span>  <span class="token generics"><span class="token punctuation">&lt;</span>0x000000076f5d4330<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>ReentrantLock</span>$<span class="token class-name">NonfairSync</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>LockSupport</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">LockSupport</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">175</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span><span class="token punctuation">.</span><span class="token function">parkAndCheckInterrupt</span><span class="token punctuation">(</span><span class="token class-name">AbstractQueuedSynchronizer</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">836</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span><span class="token punctuation">.</span><span class="token function">acquireQueued</span><span class="token punctuation">(</span><span class="token class-name">AbstractQueuedSynchronizer</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">870</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span><span class="token punctuation">.</span><span class="token function">acquire</span><span class="token punctuation">(</span><span class="token class-name">AbstractQueuedSynchronizer</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1199</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>ReentrantLock</span>$<span class="token class-name">NonfairSync</span><span class="token punctuation">.</span><span class="token function">lock</span><span class="token punctuation">(</span><span class="token class-name">ReentrantLock</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">209</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>ReentrantLock</span><span class="token punctuation">.</span><span class="token function">lock</span><span class="token punctuation">(</span><span class="token class-name">ReentrantLock</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">285</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>nicksxs<span class="token punctuation">.</span>thread_dump_demo<span class="token punctuation">.</span></span>ThreadDumpDemoApplication</span>$<span class="token number">2.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">ThreadDumpDemoApplication</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">34</span><span class="token punctuation">)</span>

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token generics"><span class="token punctuation">&lt;</span>0x000000076f5d4360<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>ReentrantLock</span>$<span class="token class-name">NonfairSync</span><span class="token punctuation">)</span>

<span class="token string">"mythread1"</span> #<span class="token number">139</span> prio<span class="token operator">=</span><span class="token number">5</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9de873800</span> nid<span class="token operator">=</span><span class="token number">0x9a03</span> waiting on condition <span class="token punctuation">[</span><span class="token number">0x0000700006eb6000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> WAITING <span class="token punctuation">(</span>parking<span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>misc<span class="token punctuation">.</span></span>Unsafe</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">Native</span> <span class="token class-name">Method</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> parking <span class="token keyword">to</span> <span class="token namespace">wait</span> <span class="token keyword">for</span>  <span class="token generics"><span class="token punctuation">&lt;</span>0x000000076f5d4360<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>ReentrantLock</span>$<span class="token class-name">NonfairSync</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>LockSupport</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">LockSupport</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">175</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span><span class="token punctuation">.</span><span class="token function">parkAndCheckInterrupt</span><span class="token punctuation">(</span><span class="token class-name">AbstractQueuedSynchronizer</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">836</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span><span class="token punctuation">.</span><span class="token function">acquireQueued</span><span class="token punctuation">(</span><span class="token class-name">AbstractQueuedSynchronizer</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">870</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span><span class="token punctuation">.</span><span class="token function">acquire</span><span class="token punctuation">(</span><span class="token class-name">AbstractQueuedSynchronizer</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1199</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>ReentrantLock</span>$<span class="token class-name">NonfairSync</span><span class="token punctuation">.</span><span class="token function">lock</span><span class="token punctuation">(</span><span class="token class-name">ReentrantLock</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">209</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>ReentrantLock</span><span class="token punctuation">.</span><span class="token function">lock</span><span class="token punctuation">(</span><span class="token class-name">ReentrantLock</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">285</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>nicksxs<span class="token punctuation">.</span>thread_dump_demo<span class="token punctuation">.</span></span>ThreadDumpDemoApplication</span>$<span class="token number">1.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">ThreadDumpDemoApplication</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">22</span><span class="token punctuation">)</span>

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token generics"><span class="token punctuation">&lt;</span>0x000000076f5d4330<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>ReentrantLock</span>$<span class="token class-name">NonfairSync</span><span class="token punctuation">)</span>

<span class="token string">"http-nio-8080-Acceptor"</span> #<span class="token number">137</span> daemon prio<span class="token operator">=</span><span class="token number">5</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9de1ac000</span> nid<span class="token operator">=</span><span class="token number">0x9b03</span> runnable <span class="token punctuation">[</span><span class="token number">0x0000700006db3000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> RUNNABLE
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>nio<span class="token punctuation">.</span>ch<span class="token punctuation">.</span></span>ServerSocketChannelImpl</span><span class="token punctuation">.</span><span class="token function">accept0</span><span class="token punctuation">(</span><span class="token class-name">Native</span> <span class="token class-name">Method</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>nio<span class="token punctuation">.</span>ch<span class="token punctuation">.</span></span>ServerSocketChannelImpl</span><span class="token punctuation">.</span><span class="token function">accept</span><span class="token punctuation">(</span><span class="token class-name">ServerSocketChannelImpl</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">422</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>nio<span class="token punctuation">.</span>ch<span class="token punctuation">.</span></span>ServerSocketChannelImpl</span><span class="token punctuation">.</span><span class="token function">accept</span><span class="token punctuation">(</span><span class="token class-name">ServerSocketChannelImpl</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">250</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> locked <span class="token generics"><span class="token punctuation">&lt;</span>0x000000076f1e4820<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Object</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>net<span class="token punctuation">.</span></span>NioEndpoint</span><span class="token punctuation">.</span><span class="token function">serverSocketAccept</span><span class="token punctuation">(</span><span class="token class-name">NioEndpoint</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">469</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>net<span class="token punctuation">.</span></span>NioEndpoint</span><span class="token punctuation">.</span><span class="token function">serverSocketAccept</span><span class="token punctuation">(</span><span class="token class-name">NioEndpoint</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">71</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>net<span class="token punctuation">.</span></span>Acceptor</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">Acceptor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">95</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">748</span><span class="token punctuation">)</span>

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token class-name">None</span>

<span class="token string">"http-nio-8080-ClientPoller"</span> #<span class="token number">136</span> daemon prio<span class="token operator">=</span><span class="token number">5</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9dd876800</span> nid<span class="token operator">=</span><span class="token number">0x6503</span> runnable <span class="token punctuation">[</span><span class="token number">0x0000700006cb0000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> RUNNABLE
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>nio<span class="token punctuation">.</span>ch<span class="token punctuation">.</span></span>KQueueArrayWrapper</span><span class="token punctuation">.</span><span class="token function">kevent0</span><span class="token punctuation">(</span><span class="token class-name">Native</span> <span class="token class-name">Method</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>nio<span class="token punctuation">.</span>ch<span class="token punctuation">.</span></span>KQueueArrayWrapper</span><span class="token punctuation">.</span><span class="token function">poll</span><span class="token punctuation">(</span><span class="token class-name">KQueueArrayWrapper</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">198</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>nio<span class="token punctuation">.</span>ch<span class="token punctuation">.</span></span>KQueueSelectorImpl</span><span class="token punctuation">.</span><span class="token function">doSelect</span><span class="token punctuation">(</span><span class="token class-name">KQueueSelectorImpl</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">117</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>nio<span class="token punctuation">.</span>ch<span class="token punctuation">.</span></span>SelectorImpl</span><span class="token punctuation">.</span><span class="token function">lockAndDoSelect</span><span class="token punctuation">(</span><span class="token class-name">SelectorImpl</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">86</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> locked <span class="token generics"><span class="token punctuation">&lt;</span>0x000000076f2978c8<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>nio<span class="token punctuation">.</span>ch<span class="token punctuation">.</span></span>Util</span>$<span class="token number">3</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> locked <span class="token generics"><span class="token punctuation">&lt;</span>0x000000076f2978b8<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span></span>Collections</span>$<span class="token class-name">UnmodifiableSet</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> locked <span class="token generics"><span class="token punctuation">&lt;</span>0x000000076f297798<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>nio<span class="token punctuation">.</span>ch<span class="token punctuation">.</span></span>KQueueSelectorImpl</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>nio<span class="token punctuation">.</span>ch<span class="token punctuation">.</span></span>SelectorImpl</span><span class="token punctuation">.</span><span class="token function">select</span><span class="token punctuation">(</span><span class="token class-name">SelectorImpl</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">97</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>net<span class="token punctuation">.</span></span>NioEndpoint</span>$<span class="token class-name">Poller</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">NioEndpoint</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">709</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">748</span><span class="token punctuation">)</span>

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token class-name">None</span>

<span class="token string">"http-nio-8080-exec-10"</span> #<span class="token number">135</span> daemon prio<span class="token operator">=</span><span class="token number">5</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9de1af000</span> nid<span class="token operator">=</span><span class="token number">0x9d03</span> waiting on condition <span class="token punctuation">[</span><span class="token number">0x0000700006bad000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> WAITING <span class="token punctuation">(</span>parking<span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>misc<span class="token punctuation">.</span></span>Unsafe</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">Native</span> <span class="token class-name">Method</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> parking <span class="token keyword">to</span> <span class="token namespace">wait</span> <span class="token keyword">for</span>  <span class="token generics"><span class="token punctuation">&lt;</span>0x000000076f26aa00<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>$<span class="token class-name">ConditionObject</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>LockSupport</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">LockSupport</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">175</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>$<span class="token class-name">ConditionObject</span><span class="token punctuation">.</span><span class="token function">await</span><span class="token punctuation">(</span><span class="token class-name">AbstractQueuedSynchronizer</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">2039</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>LinkedBlockingQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">LinkedBlockingQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">442</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">TaskQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">107</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">TaskQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">33</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span><span class="token punctuation">.</span><span class="token function">getTask</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1074</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span><span class="token punctuation">.</span><span class="token function">runWorker</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1134</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span>$<span class="token class-name">Worker</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">624</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskThread</span>$<span class="token class-name">WrappingRunnable</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">TaskThread</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">61</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">748</span><span class="token punctuation">)</span>

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token class-name">None</span>

<span class="token string">"http-nio-8080-exec-9"</span> #<span class="token number">134</span> daemon prio<span class="token operator">=</span><span class="token number">5</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9de1ab800</span> nid<span class="token operator">=</span><span class="token number">0x6403</span> waiting on condition <span class="token punctuation">[</span><span class="token number">0x0000700006aaa000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> WAITING <span class="token punctuation">(</span>parking<span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>misc<span class="token punctuation">.</span></span>Unsafe</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">Native</span> <span class="token class-name">Method</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> parking <span class="token keyword">to</span> <span class="token namespace">wait</span> <span class="token keyword">for</span>  <span class="token generics"><span class="token punctuation">&lt;</span>0x000000076f26aa00<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>$<span class="token class-name">ConditionObject</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>LockSupport</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">LockSupport</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">175</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>$<span class="token class-name">ConditionObject</span><span class="token punctuation">.</span><span class="token function">await</span><span class="token punctuation">(</span><span class="token class-name">AbstractQueuedSynchronizer</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">2039</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>LinkedBlockingQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">LinkedBlockingQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">442</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">TaskQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">107</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">TaskQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">33</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span><span class="token punctuation">.</span><span class="token function">getTask</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1074</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span><span class="token punctuation">.</span><span class="token function">runWorker</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1134</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span>$<span class="token class-name">Worker</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">624</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskThread</span>$<span class="token class-name">WrappingRunnable</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">TaskThread</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">61</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">748</span><span class="token punctuation">)</span>

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token class-name">None</span>

<span class="token string">"http-nio-8080-exec-8"</span> #<span class="token number">133</span> daemon prio<span class="token operator">=</span><span class="token number">5</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9de873000</span> nid<span class="token operator">=</span><span class="token number">0x9f03</span> waiting on condition <span class="token punctuation">[</span><span class="token number">0x00007000069a7000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> WAITING <span class="token punctuation">(</span>parking<span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>misc<span class="token punctuation">.</span></span>Unsafe</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">Native</span> <span class="token class-name">Method</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> parking <span class="token keyword">to</span> <span class="token namespace">wait</span> <span class="token keyword">for</span>  <span class="token generics"><span class="token punctuation">&lt;</span>0x000000076f26aa00<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>$<span class="token class-name">ConditionObject</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>LockSupport</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">LockSupport</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">175</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>$<span class="token class-name">ConditionObject</span><span class="token punctuation">.</span><span class="token function">await</span><span class="token punctuation">(</span><span class="token class-name">AbstractQueuedSynchronizer</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">2039</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>LinkedBlockingQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">LinkedBlockingQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">442</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">TaskQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">107</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">TaskQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">33</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span><span class="token punctuation">.</span><span class="token function">getTask</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1074</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span><span class="token punctuation">.</span><span class="token function">runWorker</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1134</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span>$<span class="token class-name">Worker</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">624</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskThread</span>$<span class="token class-name">WrappingRunnable</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">TaskThread</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">61</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">748</span><span class="token punctuation">)</span>

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token class-name">None</span>

<span class="token string">"http-nio-8080-exec-7"</span> #<span class="token number">132</span> daemon prio<span class="token operator">=</span><span class="token number">5</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9df0a1800</span> nid<span class="token operator">=</span><span class="token number">0xa103</span> waiting on condition <span class="token punctuation">[</span><span class="token number">0x00007000068a4000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> WAITING <span class="token punctuation">(</span>parking<span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>misc<span class="token punctuation">.</span></span>Unsafe</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">Native</span> <span class="token class-name">Method</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> parking <span class="token keyword">to</span> <span class="token namespace">wait</span> <span class="token keyword">for</span>  <span class="token generics"><span class="token punctuation">&lt;</span>0x000000076f26aa00<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>$<span class="token class-name">ConditionObject</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>LockSupport</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">LockSupport</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">175</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>$<span class="token class-name">ConditionObject</span><span class="token punctuation">.</span><span class="token function">await</span><span class="token punctuation">(</span><span class="token class-name">AbstractQueuedSynchronizer</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">2039</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>LinkedBlockingQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">LinkedBlockingQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">442</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">TaskQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">107</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">TaskQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">33</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span><span class="token punctuation">.</span><span class="token function">getTask</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1074</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span><span class="token punctuation">.</span><span class="token function">runWorker</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1134</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span>$<span class="token class-name">Worker</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">624</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskThread</span>$<span class="token class-name">WrappingRunnable</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">TaskThread</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">61</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">748</span><span class="token punctuation">)</span>

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token class-name">None</span>

<span class="token string">"http-nio-8080-exec-6"</span> #<span class="token number">131</span> daemon prio<span class="token operator">=</span><span class="token number">5</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9df242800</span> nid<span class="token operator">=</span><span class="token number">0x6103</span> waiting on condition <span class="token punctuation">[</span><span class="token number">0x00007000067a1000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> WAITING <span class="token punctuation">(</span>parking<span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>misc<span class="token punctuation">.</span></span>Unsafe</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">Native</span> <span class="token class-name">Method</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> parking <span class="token keyword">to</span> <span class="token namespace">wait</span> <span class="token keyword">for</span>  <span class="token generics"><span class="token punctuation">&lt;</span>0x000000076f26aa00<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>$<span class="token class-name">ConditionObject</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>LockSupport</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">LockSupport</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">175</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>$<span class="token class-name">ConditionObject</span><span class="token punctuation">.</span><span class="token function">await</span><span class="token punctuation">(</span><span class="token class-name">AbstractQueuedSynchronizer</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">2039</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>LinkedBlockingQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">LinkedBlockingQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">442</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">TaskQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">107</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">TaskQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">33</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span><span class="token punctuation">.</span><span class="token function">getTask</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1074</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span><span class="token punctuation">.</span><span class="token function">runWorker</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1134</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span>$<span class="token class-name">Worker</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">624</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskThread</span>$<span class="token class-name">WrappingRunnable</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">TaskThread</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">61</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">748</span><span class="token punctuation">)</span>

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token class-name">None</span>

<span class="token string">"http-nio-8080-exec-5"</span> #<span class="token number">130</span> daemon prio<span class="token operator">=</span><span class="token number">5</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9de872000</span> nid<span class="token operator">=</span><span class="token number">0x5f03</span> waiting on condition <span class="token punctuation">[</span><span class="token number">0x000070000669e000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> WAITING <span class="token punctuation">(</span>parking<span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>misc<span class="token punctuation">.</span></span>Unsafe</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">Native</span> <span class="token class-name">Method</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> parking <span class="token keyword">to</span> <span class="token namespace">wait</span> <span class="token keyword">for</span>  <span class="token generics"><span class="token punctuation">&lt;</span>0x000000076f26aa00<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>$<span class="token class-name">ConditionObject</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>LockSupport</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">LockSupport</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">175</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>$<span class="token class-name">ConditionObject</span><span class="token punctuation">.</span><span class="token function">await</span><span class="token punctuation">(</span><span class="token class-name">AbstractQueuedSynchronizer</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">2039</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>LinkedBlockingQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">LinkedBlockingQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">442</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">TaskQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">107</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">TaskQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">33</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span><span class="token punctuation">.</span><span class="token function">getTask</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1074</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span><span class="token punctuation">.</span><span class="token function">runWorker</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1134</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span>$<span class="token class-name">Worker</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">624</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskThread</span>$<span class="token class-name">WrappingRunnable</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">TaskThread</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">61</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">748</span><span class="token punctuation">)</span>

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token class-name">None</span>

<span class="token string">"http-nio-8080-exec-4"</span> #<span class="token number">129</span> daemon prio<span class="token operator">=</span><span class="token number">5</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9de1a6000</span> nid<span class="token operator">=</span><span class="token number">0x5e03</span> waiting on condition <span class="token punctuation">[</span><span class="token number">0x000070000659b000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> WAITING <span class="token punctuation">(</span>parking<span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>misc<span class="token punctuation">.</span></span>Unsafe</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">Native</span> <span class="token class-name">Method</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> parking <span class="token keyword">to</span> <span class="token namespace">wait</span> <span class="token keyword">for</span>  <span class="token generics"><span class="token punctuation">&lt;</span>0x000000076f26aa00<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>$<span class="token class-name">ConditionObject</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>LockSupport</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">LockSupport</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">175</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>$<span class="token class-name">ConditionObject</span><span class="token punctuation">.</span><span class="token function">await</span><span class="token punctuation">(</span><span class="token class-name">AbstractQueuedSynchronizer</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">2039</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>LinkedBlockingQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">LinkedBlockingQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">442</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">TaskQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">107</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">TaskQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">33</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span><span class="token punctuation">.</span><span class="token function">getTask</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1074</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span><span class="token punctuation">.</span><span class="token function">runWorker</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1134</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span>$<span class="token class-name">Worker</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">624</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskThread</span>$<span class="token class-name">WrappingRunnable</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">TaskThread</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">61</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">748</span><span class="token punctuation">)</span>

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token class-name">None</span>

<span class="token string">"http-nio-8080-exec-3"</span> #<span class="token number">128</span> daemon prio<span class="token operator">=</span><span class="token number">5</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9de871800</span> nid<span class="token operator">=</span><span class="token number">0x5c03</span> waiting on condition <span class="token punctuation">[</span><span class="token number">0x0000700006498000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> WAITING <span class="token punctuation">(</span>parking<span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>misc<span class="token punctuation">.</span></span>Unsafe</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">Native</span> <span class="token class-name">Method</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> parking <span class="token keyword">to</span> <span class="token namespace">wait</span> <span class="token keyword">for</span>  <span class="token generics"><span class="token punctuation">&lt;</span>0x000000076f26aa00<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>$<span class="token class-name">ConditionObject</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>LockSupport</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">LockSupport</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">175</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>$<span class="token class-name">ConditionObject</span><span class="token punctuation">.</span><span class="token function">await</span><span class="token punctuation">(</span><span class="token class-name">AbstractQueuedSynchronizer</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">2039</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>LinkedBlockingQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">LinkedBlockingQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">442</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">TaskQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">107</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">TaskQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">33</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span><span class="token punctuation">.</span><span class="token function">getTask</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1074</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span><span class="token punctuation">.</span><span class="token function">runWorker</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1134</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span>$<span class="token class-name">Worker</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">624</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskThread</span>$<span class="token class-name">WrappingRunnable</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">TaskThread</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">61</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">748</span><span class="token punctuation">)</span>

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token class-name">None</span>

<span class="token string">"http-nio-8080-exec-2"</span> #<span class="token number">127</span> daemon prio<span class="token operator">=</span><span class="token number">5</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9dead9000</span> nid<span class="token operator">=</span><span class="token number">0x5b03</span> waiting on condition <span class="token punctuation">[</span><span class="token number">0x0000700006395000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> WAITING <span class="token punctuation">(</span>parking<span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>misc<span class="token punctuation">.</span></span>Unsafe</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">Native</span> <span class="token class-name">Method</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> parking <span class="token keyword">to</span> <span class="token namespace">wait</span> <span class="token keyword">for</span>  <span class="token generics"><span class="token punctuation">&lt;</span>0x000000076f26aa00<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>$<span class="token class-name">ConditionObject</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>LockSupport</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">LockSupport</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">175</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>$<span class="token class-name">ConditionObject</span><span class="token punctuation">.</span><span class="token function">await</span><span class="token punctuation">(</span><span class="token class-name">AbstractQueuedSynchronizer</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">2039</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>LinkedBlockingQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">LinkedBlockingQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">442</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">TaskQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">107</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">TaskQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">33</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span><span class="token punctuation">.</span><span class="token function">getTask</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1074</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span><span class="token punctuation">.</span><span class="token function">runWorker</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1134</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span>$<span class="token class-name">Worker</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">624</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskThread</span>$<span class="token class-name">WrappingRunnable</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">TaskThread</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">61</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">748</span><span class="token punctuation">)</span>

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token class-name">None</span>

<span class="token string">"http-nio-8080-exec-1"</span> #<span class="token number">126</span> daemon prio<span class="token operator">=</span><span class="token number">5</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9ddb00000</span> nid<span class="token operator">=</span><span class="token number">0x5a03</span> waiting on condition <span class="token punctuation">[</span><span class="token number">0x0000700006292000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> WAITING <span class="token punctuation">(</span>parking<span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>misc<span class="token punctuation">.</span></span>Unsafe</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">Native</span> <span class="token class-name">Method</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> parking <span class="token keyword">to</span> <span class="token namespace">wait</span> <span class="token keyword">for</span>  <span class="token generics"><span class="token punctuation">&lt;</span>0x000000076f26aa00<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>$<span class="token class-name">ConditionObject</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>LockSupport</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">LockSupport</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">175</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>$<span class="token class-name">ConditionObject</span><span class="token punctuation">.</span><span class="token function">await</span><span class="token punctuation">(</span><span class="token class-name">AbstractQueuedSynchronizer</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">2039</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>LinkedBlockingQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">LinkedBlockingQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">442</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">TaskQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">107</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">TaskQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">33</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span><span class="token punctuation">.</span><span class="token function">getTask</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1074</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span><span class="token punctuation">.</span><span class="token function">runWorker</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1134</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span>$<span class="token class-name">Worker</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">624</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskThread</span>$<span class="token class-name">WrappingRunnable</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">TaskThread</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">61</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">748</span><span class="token punctuation">)</span>

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token class-name">None</span>

<span class="token string">"http-nio-8080-BlockPoller"</span> #<span class="token number">125</span> daemon prio<span class="token operator">=</span><span class="token number">5</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9df242000</span> nid<span class="token operator">=</span><span class="token number">0xa503</span> runnable <span class="token punctuation">[</span><span class="token number">0x000070000618f000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> RUNNABLE
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>nio<span class="token punctuation">.</span>ch<span class="token punctuation">.</span></span>KQueueArrayWrapper</span><span class="token punctuation">.</span><span class="token function">kevent0</span><span class="token punctuation">(</span><span class="token class-name">Native</span> <span class="token class-name">Method</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>nio<span class="token punctuation">.</span>ch<span class="token punctuation">.</span></span>KQueueArrayWrapper</span><span class="token punctuation">.</span><span class="token function">poll</span><span class="token punctuation">(</span><span class="token class-name">KQueueArrayWrapper</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">198</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>nio<span class="token punctuation">.</span>ch<span class="token punctuation">.</span></span>KQueueSelectorImpl</span><span class="token punctuation">.</span><span class="token function">doSelect</span><span class="token punctuation">(</span><span class="token class-name">KQueueSelectorImpl</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">117</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>nio<span class="token punctuation">.</span>ch<span class="token punctuation">.</span></span>SelectorImpl</span><span class="token punctuation">.</span><span class="token function">lockAndDoSelect</span><span class="token punctuation">(</span><span class="token class-name">SelectorImpl</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">86</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> locked <span class="token generics"><span class="token punctuation">&lt;</span>0x000000076f1eea30<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>nio<span class="token punctuation">.</span>ch<span class="token punctuation">.</span></span>Util</span>$<span class="token number">3</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> locked <span class="token generics"><span class="token punctuation">&lt;</span>0x000000076f1ee198<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span></span>Collections</span>$<span class="token class-name">UnmodifiableSet</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> locked <span class="token generics"><span class="token punctuation">&lt;</span>0x000000076f1ee010<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>nio<span class="token punctuation">.</span>ch<span class="token punctuation">.</span></span>KQueueSelectorImpl</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>nio<span class="token punctuation">.</span>ch<span class="token punctuation">.</span></span>SelectorImpl</span><span class="token punctuation">.</span><span class="token function">select</span><span class="token punctuation">(</span><span class="token class-name">SelectorImpl</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">97</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>net<span class="token punctuation">.</span></span>NioBlockingSelector</span>$<span class="token class-name">BlockPoller</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">NioBlockingSelector</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">313</span><span class="token punctuation">)</span>

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token class-name">None</span>

<span class="token string">"container-0"</span> #<span class="token number">124</span> prio<span class="token operator">=</span><span class="token number">5</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9df06a000</span> nid<span class="token operator">=</span><span class="token number">0x5803</span> waiting on condition <span class="token punctuation">[</span><span class="token number">0x000070000608c000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> TIMED_WAITING <span class="token punctuation">(</span>sleeping<span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread</span><span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token class-name">Native</span> <span class="token class-name">Method</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>catalina<span class="token punctuation">.</span>core<span class="token punctuation">.</span></span>StandardServer</span><span class="token punctuation">.</span><span class="token function">await</span><span class="token punctuation">(</span><span class="token class-name">StandardServer</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">570</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>boot<span class="token punctuation">.</span>web<span class="token punctuation">.</span>embedded<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span></span>TomcatWebServer</span>$<span class="token number">1.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">TomcatWebServer</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">197</span><span class="token punctuation">)</span>

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token class-name">None</span>

<span class="token string">"Catalina-utility-2"</span> #<span class="token number">123</span> prio<span class="token operator">=</span><span class="token number">1</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9de886000</span> nid<span class="token operator">=</span><span class="token number">0xa80f</span> waiting on condition <span class="token punctuation">[</span><span class="token number">0x0000700005f89000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> WAITING <span class="token punctuation">(</span>parking<span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>misc<span class="token punctuation">.</span></span>Unsafe</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">Native</span> <span class="token class-name">Method</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> parking <span class="token keyword">to</span> <span class="token namespace">wait</span> <span class="token keyword">for</span>  <span class="token generics"><span class="token punctuation">&lt;</span>0x000000076c88ab58<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>$<span class="token class-name">ConditionObject</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>LockSupport</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">LockSupport</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">175</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>$<span class="token class-name">ConditionObject</span><span class="token punctuation">.</span><span class="token function">await</span><span class="token punctuation">(</span><span class="token class-name">AbstractQueuedSynchronizer</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">2039</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ScheduledThreadPoolExecutor</span>$<span class="token class-name">DelayedWorkQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">ScheduledThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1088</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ScheduledThreadPoolExecutor</span>$<span class="token class-name">DelayedWorkQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">ScheduledThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">809</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span><span class="token punctuation">.</span><span class="token function">getTask</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1074</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span><span class="token punctuation">.</span><span class="token function">runWorker</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1134</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span>$<span class="token class-name">Worker</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">624</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskThread</span>$<span class="token class-name">WrappingRunnable</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">TaskThread</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">61</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">748</span><span class="token punctuation">)</span>

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token class-name">None</span>

<span class="token string">"Catalina-utility-1"</span> #<span class="token number">122</span> prio<span class="token operator">=</span><span class="token number">1</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9de884000</span> nid<span class="token operator">=</span><span class="token number">0x5667</span> waiting on condition <span class="token punctuation">[</span><span class="token number">0x0000700005e86000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> TIMED_WAITING <span class="token punctuation">(</span>parking<span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>misc<span class="token punctuation">.</span></span>Unsafe</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">Native</span> <span class="token class-name">Method</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> parking <span class="token keyword">to</span> <span class="token namespace">wait</span> <span class="token keyword">for</span>  <span class="token generics"><span class="token punctuation">&lt;</span>0x000000076c88ab58<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>$<span class="token class-name">ConditionObject</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>LockSupport</span><span class="token punctuation">.</span><span class="token function">parkNanos</span><span class="token punctuation">(</span><span class="token class-name">LockSupport</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">215</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>$<span class="token class-name">ConditionObject</span><span class="token punctuation">.</span><span class="token function">awaitNanos</span><span class="token punctuation">(</span><span class="token class-name">AbstractQueuedSynchronizer</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">2078</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ScheduledThreadPoolExecutor</span>$<span class="token class-name">DelayedWorkQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">ScheduledThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1093</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ScheduledThreadPoolExecutor</span>$<span class="token class-name">DelayedWorkQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">ScheduledThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">809</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span><span class="token punctuation">.</span><span class="token function">getTask</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1074</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span><span class="token punctuation">.</span><span class="token function">runWorker</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1134</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span>$<span class="token class-name">Worker</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">624</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>tomcat<span class="token punctuation">.</span>util<span class="token punctuation">.</span>threads<span class="token punctuation">.</span></span>TaskThread</span>$<span class="token class-name">WrappingRunnable</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">TaskThread</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">61</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">748</span><span class="token punctuation">)</span>

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token class-name">None</span>

<span class="token string">"RMI Scheduler(0)"</span> #<span class="token number">15</span> daemon prio<span class="token operator">=</span><span class="token number">5</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9de9ee000</span> nid<span class="token operator">=</span><span class="token number">0x5503</span> waiting on condition <span class="token punctuation">[</span><span class="token number">0x0000700005d83000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> TIMED_WAITING <span class="token punctuation">(</span>parking<span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>misc<span class="token punctuation">.</span></span>Unsafe</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">Native</span> <span class="token class-name">Method</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> parking <span class="token keyword">to</span> <span class="token namespace">wait</span> <span class="token keyword">for</span>  <span class="token generics"><span class="token punctuation">&lt;</span>0x00000006c0015410<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>$<span class="token class-name">ConditionObject</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>LockSupport</span><span class="token punctuation">.</span><span class="token function">parkNanos</span><span class="token punctuation">(</span><span class="token class-name">LockSupport</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">215</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>$<span class="token class-name">ConditionObject</span><span class="token punctuation">.</span><span class="token function">awaitNanos</span><span class="token punctuation">(</span><span class="token class-name">AbstractQueuedSynchronizer</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">2078</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ScheduledThreadPoolExecutor</span>$<span class="token class-name">DelayedWorkQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">ScheduledThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1093</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ScheduledThreadPoolExecutor</span>$<span class="token class-name">DelayedWorkQueue</span><span class="token punctuation">.</span><span class="token function">take</span><span class="token punctuation">(</span><span class="token class-name">ScheduledThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">809</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span><span class="token punctuation">.</span><span class="token function">getTask</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1074</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span><span class="token punctuation">.</span><span class="token function">runWorker</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1134</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span></span>ThreadPoolExecutor</span>$<span class="token class-name">Worker</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">624</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">748</span><span class="token punctuation">)</span>

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token class-name">None</span>

<span class="token string">"Attach Listener"</span> #<span class="token number">13</span> daemon prio<span class="token operator">=</span><span class="token number">9</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9df149800</span> nid<span class="token operator">=</span><span class="token number">0x3c07</span> waiting on condition <span class="token punctuation">[</span><span class="token number">0x0000000000000000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> RUNNABLE

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token class-name">None</span>

<span class="token string">"RMI TCP Accept-0"</span> #<span class="token number">11</span> daemon prio<span class="token operator">=</span><span class="token number">5</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9df100000</span> nid<span class="token operator">=</span><span class="token number">0x4003</span> runnable <span class="token punctuation">[</span><span class="token number">0x0000700005977000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> RUNNABLE
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>net<span class="token punctuation">.</span></span>PlainSocketImpl</span><span class="token punctuation">.</span><span class="token function">socketAccept</span><span class="token punctuation">(</span><span class="token class-name">Native</span> <span class="token class-name">Method</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>net<span class="token punctuation">.</span></span>AbstractPlainSocketImpl</span><span class="token punctuation">.</span><span class="token function">accept</span><span class="token punctuation">(</span><span class="token class-name">AbstractPlainSocketImpl</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">409</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>net<span class="token punctuation">.</span></span>ServerSocket</span><span class="token punctuation">.</span><span class="token function">implAccept</span><span class="token punctuation">(</span><span class="token class-name">ServerSocket</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">545</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>net<span class="token punctuation">.</span></span>ServerSocket</span><span class="token punctuation">.</span><span class="token function">accept</span><span class="token punctuation">(</span><span class="token class-name">ServerSocket</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">513</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>management<span class="token punctuation">.</span>jmxremote<span class="token punctuation">.</span></span>LocalRMIServerSocketFactory</span>$<span class="token number">1.</span><span class="token function">accept</span><span class="token punctuation">(</span><span class="token class-name">LocalRMIServerSocketFactory</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">52</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>rmi<span class="token punctuation">.</span>transport<span class="token punctuation">.</span>tcp<span class="token punctuation">.</span></span>TCPTransport</span>$<span class="token class-name">AcceptLoop</span><span class="token punctuation">.</span><span class="token function">executeAcceptLoop</span><span class="token punctuation">(</span><span class="token class-name">TCPTransport</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">405</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>rmi<span class="token punctuation">.</span>transport<span class="token punctuation">.</span>tcp<span class="token punctuation">.</span></span>TCPTransport</span>$<span class="token class-name">AcceptLoop</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">TCPTransport</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">377</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">748</span><span class="token punctuation">)</span>

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token class-name">None</span>

<span class="token string">"Service Thread"</span> #<span class="token number">9</span> daemon prio<span class="token operator">=</span><span class="token number">9</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9df0ce800</span> nid<span class="token operator">=</span><span class="token number">0x4103</span> runnable <span class="token punctuation">[</span><span class="token number">0x0000000000000000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> RUNNABLE

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token class-name">None</span>

<span class="token string">"C1 CompilerThread2"</span> #<span class="token number">8</span> daemon prio<span class="token operator">=</span><span class="token number">9</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9df0ce000</span> nid<span class="token operator">=</span><span class="token number">0x4203</span> waiting on condition <span class="token punctuation">[</span><span class="token number">0x0000000000000000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> RUNNABLE

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token class-name">None</span>

<span class="token string">"C2 CompilerThread1"</span> #<span class="token number">7</span> daemon prio<span class="token operator">=</span><span class="token number">9</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9de0a3800</span> nid<span class="token operator">=</span><span class="token number">0x3503</span> waiting on condition <span class="token punctuation">[</span><span class="token number">0x0000000000000000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> RUNNABLE

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token class-name">None</span>

<span class="token string">"C2 CompilerThread0"</span> #<span class="token number">6</span> daemon prio<span class="token operator">=</span><span class="token number">9</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9de89b000</span> nid<span class="token operator">=</span><span class="token number">0x3403</span> waiting on condition <span class="token punctuation">[</span><span class="token number">0x0000000000000000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> RUNNABLE

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token class-name">None</span>

<span class="token string">"Monitor Ctrl-Break"</span> #<span class="token number">5</span> daemon prio<span class="token operator">=</span><span class="token number">5</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9df0ca000</span> nid<span class="token operator">=</span><span class="token number">0x3303</span> runnable <span class="token punctuation">[</span><span class="token number">0x0000700005468000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> RUNNABLE
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>net<span class="token punctuation">.</span></span>SocketInputStream</span><span class="token punctuation">.</span><span class="token function">socketRead0</span><span class="token punctuation">(</span><span class="token class-name">Native</span> <span class="token class-name">Method</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>net<span class="token punctuation">.</span></span>SocketInputStream</span><span class="token punctuation">.</span><span class="token function">socketRead</span><span class="token punctuation">(</span><span class="token class-name">SocketInputStream</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">116</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>net<span class="token punctuation">.</span></span>SocketInputStream</span><span class="token punctuation">.</span><span class="token function">read</span><span class="token punctuation">(</span><span class="token class-name">SocketInputStream</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">171</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>net<span class="token punctuation">.</span></span>SocketInputStream</span><span class="token punctuation">.</span><span class="token function">read</span><span class="token punctuation">(</span><span class="token class-name">SocketInputStream</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">141</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>nio<span class="token punctuation">.</span>cs<span class="token punctuation">.</span></span>StreamDecoder</span><span class="token punctuation">.</span><span class="token function">readBytes</span><span class="token punctuation">(</span><span class="token class-name">StreamDecoder</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">284</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>nio<span class="token punctuation">.</span>cs<span class="token punctuation">.</span></span>StreamDecoder</span><span class="token punctuation">.</span><span class="token function">implRead</span><span class="token punctuation">(</span><span class="token class-name">StreamDecoder</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">326</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>nio<span class="token punctuation">.</span>cs<span class="token punctuation">.</span></span>StreamDecoder</span><span class="token punctuation">.</span><span class="token function">read</span><span class="token punctuation">(</span><span class="token class-name">StreamDecoder</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">178</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> locked <span class="token generics"><span class="token punctuation">&lt;</span>0x00000006c001b760<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>io<span class="token punctuation">.</span></span>InputStreamReader</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>io<span class="token punctuation">.</span></span>InputStreamReader</span><span class="token punctuation">.</span><span class="token function">read</span><span class="token punctuation">(</span><span class="token class-name">InputStreamReader</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">184</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>io<span class="token punctuation">.</span></span>BufferedReader</span><span class="token punctuation">.</span><span class="token function">fill</span><span class="token punctuation">(</span><span class="token class-name">BufferedReader</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">161</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>io<span class="token punctuation">.</span></span>BufferedReader</span><span class="token punctuation">.</span><span class="token function">readLine</span><span class="token punctuation">(</span><span class="token class-name">BufferedReader</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">324</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> locked <span class="token generics"><span class="token punctuation">&lt;</span>0x00000006c001b760<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>io<span class="token punctuation">.</span></span>InputStreamReader</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>io<span class="token punctuation">.</span></span>BufferedReader</span><span class="token punctuation">.</span><span class="token function">readLine</span><span class="token punctuation">(</span><span class="token class-name">BufferedReader</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">389</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>intellij<span class="token punctuation">.</span>rt<span class="token punctuation">.</span>execution<span class="token punctuation">.</span>application<span class="token punctuation">.</span></span>AppMainV2</span>$<span class="token number">1.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">AppMainV2</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">64</span><span class="token punctuation">)</span>

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token class-name">None</span>

<span class="token string">"Signal Dispatcher"</span> #<span class="token number">4</span> daemon prio<span class="token operator">=</span><span class="token number">9</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9de824000</span> nid<span class="token operator">=</span><span class="token number">0x4503</span> runnable <span class="token punctuation">[</span><span class="token number">0x0000000000000000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> RUNNABLE

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token class-name">None</span>

<span class="token string">"Finalizer"</span> #<span class="token number">3</span> daemon prio<span class="token operator">=</span><span class="token number">8</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9dd811800</span> nid<span class="token operator">=</span><span class="token number">0x4f03</span> in <span class="token class-name">Object</span><span class="token punctuation">.</span><span class="token function">wait</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">[</span><span class="token number">0x0000700005262000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> WAITING <span class="token punctuation">(</span>on object monitor<span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Object</span><span class="token punctuation">.</span><span class="token function">wait</span><span class="token punctuation">(</span><span class="token class-name">Native</span> <span class="token class-name">Method</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> waiting on <span class="token generics"><span class="token punctuation">&lt;</span>0x00000006c0008348<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>ref<span class="token punctuation">.</span></span>ReferenceQueue</span>$<span class="token class-name">Lock</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>ref<span class="token punctuation">.</span></span>ReferenceQueue</span><span class="token punctuation">.</span><span class="token function">remove</span><span class="token punctuation">(</span><span class="token class-name">ReferenceQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">144</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> locked <span class="token generics"><span class="token punctuation">&lt;</span>0x00000006c0008348<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>ref<span class="token punctuation">.</span></span>ReferenceQueue</span>$<span class="token class-name">Lock</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>ref<span class="token punctuation">.</span></span>ReferenceQueue</span><span class="token punctuation">.</span><span class="token function">remove</span><span class="token punctuation">(</span><span class="token class-name">ReferenceQueue</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">165</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>ref<span class="token punctuation">.</span></span>Finalizer</span>$<span class="token class-name">FinalizerThread</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">Finalizer</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">216</span><span class="token punctuation">)</span>

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token class-name">None</span>

<span class="token string">"Reference Handler"</span> #<span class="token number">2</span> daemon prio<span class="token operator">=</span><span class="token number">10</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9de02a000</span> nid<span class="token operator">=</span><span class="token number">0x5003</span> in <span class="token class-name">Object</span><span class="token punctuation">.</span><span class="token function">wait</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">[</span><span class="token number">0x000070000515f000</span><span class="token punctuation">]</span>
   <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread<span class="token punctuation">.</span>State</span><span class="token operator">:</span> WAITING <span class="token punctuation">(</span>on object monitor<span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Object</span><span class="token punctuation">.</span><span class="token function">wait</span><span class="token punctuation">(</span><span class="token class-name">Native</span> <span class="token class-name">Method</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> waiting on <span class="token generics"><span class="token punctuation">&lt;</span>0x00000006c001b940<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>ref<span class="token punctuation">.</span></span>Reference</span>$<span class="token class-name">Lock</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Object</span><span class="token punctuation">.</span><span class="token function">wait</span><span class="token punctuation">(</span><span class="token class-name">Object</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">502</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>ref<span class="token punctuation">.</span></span>Reference</span><span class="token punctuation">.</span><span class="token function">tryHandlePending</span><span class="token punctuation">(</span><span class="token class-name">Reference</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">191</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> locked <span class="token generics"><span class="token punctuation">&lt;</span>0x00000006c001b940<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>ref<span class="token punctuation">.</span></span>Reference</span>$<span class="token class-name">Lock</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>ref<span class="token punctuation">.</span></span>Reference</span>$<span class="token class-name">ReferenceHandler</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">Reference</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">153</span><span class="token punctuation">)</span>

   <span class="token class-name">Locked</span> ownable synchronizers<span class="token operator">:</span>
        <span class="token operator">-</span> <span class="token class-name">None</span>

<span class="token string">"VM Thread"</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9df00b800</span> nid<span class="token operator">=</span><span class="token number">0x2c03</span> runnable 

<span class="token string">"GC task thread#0 (ParallelGC)"</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9de805000</span> nid<span class="token operator">=</span><span class="token number">0x1e07</span> runnable 

<span class="token string">"GC task thread#1 (ParallelGC)"</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9de003800</span> nid<span class="token operator">=</span><span class="token number">0x2a03</span> runnable 

<span class="token string">"GC task thread#2 (ParallelGC)"</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9df002000</span> nid<span class="token operator">=</span><span class="token number">0x5403</span> runnable 

<span class="token string">"GC task thread#3 (ParallelGC)"</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9df002800</span> nid<span class="token operator">=</span><span class="token number">0x5203</span> runnable 

<span class="token string">"VM Periodic Task Thread"</span> os_prio<span class="token operator">=</span><span class="token number">31</span> tid<span class="token operator">=</span><span class="token number">0x00007fc9df11a800</span> nid<span class="token operator">=</span><span class="token number">0x3a03</span> waiting on condition 

JNI global references<span class="token operator">:</span> <span class="token number">1087</span>


<span class="token class-name">Found</span> one <span class="token class-name">Java</span><span class="token operator">-</span>level deadlock<span class="token operator">:</span>
<span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">=</span>
<span class="token string">"mythread2"</span><span class="token operator">:</span>
  waiting <span class="token keyword">for</span> ownable synchronizer <span class="token number">0x000000076f5d4330</span><span class="token punctuation">,</span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>ReentrantLock</span>$<span class="token class-name">NonfairSync</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
  which is held by <span class="token string">"mythread1"</span>
<span class="token string">"mythread1"</span><span class="token operator">:</span>
  waiting <span class="token keyword">for</span> ownable synchronizer <span class="token number">0x000000076f5d4360</span><span class="token punctuation">,</span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>ReentrantLock</span>$<span class="token class-name">NonfairSync</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
  which is held by <span class="token string">"mythread2"</span>

<span class="token class-name">Java</span> stack information <span class="token keyword">for</span> the threads listed above<span class="token operator">:</span>
<span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">=</span>
<span class="token string">"mythread2"</span><span class="token operator">:</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>misc<span class="token punctuation">.</span></span>Unsafe</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">Native</span> <span class="token class-name">Method</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> parking <span class="token keyword">to</span> <span class="token namespace">wait</span> <span class="token keyword">for</span>  <span class="token generics"><span class="token punctuation">&lt;</span>0x000000076f5d4330<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>ReentrantLock</span>$<span class="token class-name">NonfairSync</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>LockSupport</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">LockSupport</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">175</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span><span class="token punctuation">.</span><span class="token function">parkAndCheckInterrupt</span><span class="token punctuation">(</span><span class="token class-name">AbstractQueuedSynchronizer</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">836</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span><span class="token punctuation">.</span><span class="token function">acquireQueued</span><span class="token punctuation">(</span><span class="token class-name">AbstractQueuedSynchronizer</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">870</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span><span class="token punctuation">.</span><span class="token function">acquire</span><span class="token punctuation">(</span><span class="token class-name">AbstractQueuedSynchronizer</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1199</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>ReentrantLock</span>$<span class="token class-name">NonfairSync</span><span class="token punctuation">.</span><span class="token function">lock</span><span class="token punctuation">(</span><span class="token class-name">ReentrantLock</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">209</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>ReentrantLock</span><span class="token punctuation">.</span><span class="token function">lock</span><span class="token punctuation">(</span><span class="token class-name">ReentrantLock</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">285</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>nicksxs<span class="token punctuation">.</span>thread_dump_demo<span class="token punctuation">.</span></span>ThreadDumpDemoApplication</span>$<span class="token number">2.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">ThreadDumpDemoApplication</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">34</span><span class="token punctuation">)</span>
<span class="token string">"mythread1"</span><span class="token operator">:</span>
        at <span class="token class-name"><span class="token namespace">sun<span class="token punctuation">.</span>misc<span class="token punctuation">.</span></span>Unsafe</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">Native</span> <span class="token class-name">Method</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> parking <span class="token keyword">to</span> <span class="token namespace">wait</span> <span class="token keyword">for</span>  <span class="token generics"><span class="token punctuation">&lt;</span>0x000000076f5d4360<span class="token punctuation">></span></span> <span class="token punctuation">(</span>a <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>ReentrantLock</span>$<span class="token class-name">NonfairSync</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>LockSupport</span><span class="token punctuation">.</span><span class="token function">park</span><span class="token punctuation">(</span><span class="token class-name">LockSupport</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">175</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span><span class="token punctuation">.</span><span class="token function">parkAndCheckInterrupt</span><span class="token punctuation">(</span><span class="token class-name">AbstractQueuedSynchronizer</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">836</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span><span class="token punctuation">.</span><span class="token function">acquireQueued</span><span class="token punctuation">(</span><span class="token class-name">AbstractQueuedSynchronizer</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">870</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span><span class="token punctuation">.</span><span class="token function">acquire</span><span class="token punctuation">(</span><span class="token class-name">AbstractQueuedSynchronizer</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1199</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>ReentrantLock</span>$<span class="token class-name">NonfairSync</span><span class="token punctuation">.</span><span class="token function">lock</span><span class="token punctuation">(</span><span class="token class-name">ReentrantLock</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">209</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>ReentrantLock</span><span class="token punctuation">.</span><span class="token function">lock</span><span class="token punctuation">(</span><span class="token class-name">ReentrantLock</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">285</span><span class="token punctuation">)</span>
        at <span class="token class-name"><span class="token namespace">com<span class="token punctuation">.</span>nicksxs<span class="token punctuation">.</span>thread_dump_demo<span class="token punctuation">.</span></span>ThreadDumpDemoApplication</span>$<span class="token number">1.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">ThreadDumpDemoApplication</span><span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">22</span><span class="token punctuation">)</span>

<span class="token class-name">Found</span> <span class="token number">1</span> deadlock<span class="token punctuation">.</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>前面的信息其实上次就看过了，后面就可以发现有个死锁了，<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/a1I2vj.png"><br>上面比较长，把主要的截出来，就是这边的，这点就很强大了。</p>
<h3 id="jmap"><a href="#jmap" class="headerlink" title="jmap"></a>jmap</h3><p>惯例还是看一下帮助信息<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/dBiPqS.png"><br>这个相对命令比较多，不过因为现在 dump 下来我们可能会用文件模式，然后将文件下载下来使用 mat 进行分析，所以可以使用<br><code>jmap -dump:live,format=b,file=heap.bin &lt;pid&gt;</code><br>命令照着上面看的就是打印活着的对象，然后以二进制格式，文件名叫 heap.bin 然后最后就是进程 id，打印出来以后可以用 mat 打开<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/NRWowU.png"><br>这样就可以很清晰的看到应用里的各种信息，jmap 直接在命令中还可以看很多信息，比如使用<code>jmap -histo &lt;pid&gt;</code>打印对象的实例数和对象占用的内存<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/1GTBrY.png"><br><code>jmap -finalizerinfo &lt;pid&gt;</code> 打印正在等候回收的对象<br><img data-src="https://gitee.com/nicksxs/images/raw/master/uPic/Tb8uHP.png"></p>
<h4 id="小tips"><a href="#小tips" class="headerlink" title="小tips"></a>小tips</h4><p>对于一些应用内存已经占满了，jstack 和 jmap 可能会连不上的情况，可以使用<code>-F</code>参数强制打印线程或者 dump 文件，但是要注意这两者使用的用户必须与 java 进程启动用户一致，并且使用的 jdk 也要一致</p>
]]></content>
      <categories>
        <category>Java</category>
        <category>Thread dump</category>
        <category>问题排查</category>
        <category>工具</category>
      </categories>
      <tags>
        <tag>Java</tag>
        <tag>JPS</tag>
        <tag>JStack</tag>
        <tag>JMap</tag>
      </tags>
  </entry>
</search>
