-
Notifications
You must be signed in to change notification settings - Fork 19
/
JVM-Learn.html
1 lines (1 loc) · 161 KB
/
JVM-Learn.html
1
<!-- build time:Wed Mar 09 2022 10:17:48 GMT+0800 (GMT+08:00) --><!doctype html><html class="theme-next mist" lang="zh-Hans"><head><meta name="generator" content="Hexo 3.8.0"><meta name="google-site-verification" content="7Tau9WyVgxnsEY9oYedu9g0U6_8akOX3wiKbaYcrg9A"><meta name="baidu-site-verification" content="EVwLiaxdxX"><link href="/css/xps13.css" rel="stylesheet" type="text/css"><link href="/css/message.css" rel="stylesheet" type="text/css"><link href="//fonts.googleapis.com/css?family=Baloo+Bhaijaan|Inconsolata|Josefin+Sans|Montserrat" rel="stylesheet"><script type="text/javascript" src="/js/jquery-1.11.3.min.js"></script><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1"><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css"><link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css"><meta name="keywords" content="Java,"><link rel="alternate" href="/atom.xml" title="MrBird" type="application/atom+xml"><link rel="shortcut icon" type="image/x-icon" href="/bird.png?v=5.1.1"><meta name="description" content="JVM结构JVM(hotspot)结构概览如下图所示:上图中,灰色部分(Java栈,本地方法栈和程序计数器)是线程私有,不存在线程安全问题,橙色部分(方法区和堆)为线程共享区。"><meta name="keywords" content="Java"><meta property="og:type" content="article"><meta property="og:title" content="JVM学习笔记"><meta property="og:url" content="http://mrbird.cc/JVM-Learn.html"><meta property="og:site_name" content="MrBird"><meta property="og:description" content="JVM结构JVM(hotspot)结构概览如下图所示:上图中,灰色部分(Java栈,本地方法栈和程序计数器)是线程私有,不存在线程安全问题,橙色部分(方法区和堆)为线程共享区。"><meta property="og:locale" content="zh-Hans"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/2020-06-18%2009.33.53.gif"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/QQ20200305-105423@2x_meitu_1.jpg"><meta property="og:image" content="http://mrbird.cc/img/QQ20200305-110220@2x_meitu_2.jpg"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:image" content="http://mrbird.cc/img/[email protected]"><meta property="og:updated_time" content="2021-01-19T06:58:56.860Z"><meta name="twitter:card" content="summary"><meta name="twitter:title" content="JVM学习笔记"><meta name="twitter:description" content="JVM结构JVM(hotspot)结构概览如下图所示:上图中,灰色部分(Java栈,本地方法栈和程序计数器)是线程私有,不存在线程安全问题,橙色部分(方法区和堆)为线程共享区。"><meta name="twitter:image" content="http://mrbird.cc/img/[email protected]"><script type="text/javascript" id="hexo.configurations">var NexT=window.NexT||{},CONFIG={root:"/",scheme:"Mist",sidebar:{position:"left",display:"always",offset:12,offset_float:0,b2t:!1,scrollpercent:!0},fancybox:!1,motion:!1}</script><title>JVM学习笔记 | MrBird</title></head><body ondragstart="return!1" class="animsition" lang="zh-Hans" style="overflow-x:hidden;padding-left:280px"><script type="text/javascript" src="/js/mo.min.js"></script><style>body{text-rendering:geometricPrecision!important;font-family:'Josefin Sans','PingFang SC'!important;-webkit-font-smoothing:antialiased!important;-webkit-text-size-adjust:100%!important;background-color:#f4f6f7}@media (min-width:768px) and (max-width:991px){body .header-innerr{width:700px!important}}.header-innerr{margin:0 auto;padding:100px 0 70px;width:880px}@media (min-width:1600px){.container .header-innerr{width:996px}}.header-innerr{position:relative}.header-innerr{padding:0}.header-innerr:after,.header-innerr:before{content:" ";display:table}.header-innerr:after{clear:both}@media (max-width:767px){.header-innerr{width:auto;padding:10px;margin-bottom:-20px}}</style><div class="container sidebar-position-left page-post-detail"><div class="headband"></div><header id="header" class="header"><div class="header-inner"><div class="site-brand-wrapper"><div class="site-meta"><link href="https://fonts.font.im/css?family=Merienda" rel="stylesheet"><div class="custom-logo-site-title"></div><h1 class="site-subtitle" itemprop="description"></h1></div><div class="site-nav-toggle"><button><span class="btn-bar"></span> <span class="btn-bar"></span> <span class="btn-bar"></span></button></div></div><nav class="site-nav"><div class="site-search"><div class="popup search-popup local-search-popup"><div class="local-search-header clearfix"><span class="search-icon"><i class="fa fa-search"></i> </span><span class="popup-btn-close"><i class="fa fa-times-circle"></i></span><div class="local-search-input-wrapper"><input autocomplete="off" placeholder="Search" spellcheck="false" type="text" id="local-search-input"></div></div><div id="local-search-result"></div></div></div></nav></div><div class="header-innerr"></div></header><main id="main" class="main"><div class="main-inner"><div class="content-wrap"><div id="content" class="content"><div id="posts" class="posts-expand"><article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"><link itemprop="mainEntityOfPage" href="http://mrbird.cc/JVM-Learn.html"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="name" content="MrBird"><meta itemprop="description" content=""><meta itemprop="image" content="/images/blogImage.jpg"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="MrBird"></span><header class="post-header"><h2 class="post-title" itemprop="name headline">JVM学习笔记</h2><div class="post-meta"><span class="post-time"><span class="post-meta-item-icon"><i class="fa fa-calendar-o"></i> </span><span class="post-meta-item-text"></span> <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-04-01T11:28:58+08:00">2019-04-01 </time></span><span></span> <span class="post-meta-divider">|</span> <span class="page-pv"><i class="fa fa-laptop"></i> Visit count <span class="busuanzi-value" id="busuanzi_value_page_pv"></span></span></div></header><div class="post-body" itemprop="articleBody"><h2 id="JVM结构"><a href="#JVM结构" class="headerlink" title="JVM结构"></a>JVM结构</h2><p>JVM(hotspot)结构概览如下图所示:</p><p><img src="img/[email protected]" alt="QQ20200303-134536@2x"></p><p>上图中,灰色部分(Java栈,本地方法栈和程序计数器)是线程私有,不存在线程安全问题,橙色部分(方法区和堆)为线程共享区。</p><a id="more"></a><h2 id="类加载器"><a href="#类加载器" class="headerlink" title="类加载器"></a>类加载器</h2><p><strong>类加载器</strong>(Class Loader)负责加载class文件,class文件在文件开头有特定的标识。类加载器将class文件字节码内容加载到内存中,并将这些内容转换成<strong>方法区</strong>中的运行时数据结构。ClassLoader只负责class文件的加载,至于它是否可以运行,则由执行引擎Execution Engine决定。类加载示意图:</p><p><img src="img/[email protected]" alt="QQ20200303-155915@2x"></p><p>类加载器识别的class文件除了是<strong>.class</strong>格式外,文件的开头还得有特殊的标识,使用文本编辑器打开一个class格式的文件:</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">cafe babe 0000 0034 0010 0a00 0300 0d07</span><br><span class="line">000e 0700 0f01 0006 3c69 6e69 743e 0100</span><br><span class="line">0328 2956 0100 0443 6f64 6501 000f 4c69</span><br><span class="line">6e65 4e75 6d62 6572 5461 626c 6501 0012</span><br><span class="line">4c6f 6361 6c56 6172 6961 626c 6554 6162</span><br><span class="line">6c65 0100 0474 6869 7301 0014 4c63 632f</span><br><span class="line">6d72 6269 7264 2f63 6173 2f54 6573 743b</span><br><span class="line">0100 0a53 6f75 7263 6546 696c 6501 0009</span><br><span class="line">5465 7374 2e6a 6176 610c 0004 0005 0100</span><br><span class="line">1263 632f 6d72 6269 7264 2f63 6173 2f54</span><br><span class="line">6573 7401 0010 6a61 7661 2f6c 616e 672f</span><br><span class="line">4f62 6a65 6374 0021 0002 0003 0000 0000</span><br><span class="line">0001 0001 0004 0005 0001 0006 0000 002f</span><br><span class="line">0001 0001 0000 0005 2ab7 0001 b100 0000</span><br><span class="line">0200 0700 0000 0600 0100 0000 0300 0800</span><br><span class="line">0000 0c00 0100 0000 0500 0900 0a00 0000</span><br><span class="line">0100 0b00 0000 0200 0c</span><br></pre></td></tr></table></figure><p></p><p>这个特定的标识就是十六进制字符<strong>cafe babe</strong>。</p><h3 id="类加载器分类"><a href="#类加载器分类" class="headerlink" title="类加载器分类"></a>类加载器分类</h3><p>类加载器分为4种:</p><h4 id="启动类加载器"><a href="#启动类加载器" class="headerlink" title="启动类加载器"></a>启动类加载器</h4><p>启动类加载器BootstrapClassLoader也叫根加载器,是虚拟机自带的加载器,底层由C++实现,用于加载<code>$JAVA_HOME/jre/lib/rt.jar</code>包内的class文件。rt.jar是Java基础类库,包含Java运行环境所需的基础类:</p><p><img src="img/[email protected]" alt="QQ20200303-161919@2x"></p><p>举个例子:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>{</span><br><span class="line"> Object object = <span class="keyword">new</span> Object();</span><br><span class="line"> System.out.println(object.getClass().getClassLoader());</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p></p><p><code>Object</code>为Java自带的类,运行结果如下:</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">null</span><br></pre></td></tr></table></figure><p></p><p>并没有返回预期的BootstrapClassLoader,这是因为BootstrapClassLoader底层是由C++实现的,并非Java实现。</p><h4 id="拓展类加载器"><a href="#拓展类加载器" class="headerlink" title="拓展类加载器"></a>拓展类加载器</h4><p>拓展类加载器ExtClassLoader是虚拟机自带的加载器,由Java语言实现,用于加载<code>$JAVA_HOME/jre/lib/ext/**.jar</code>目录下的class文件:</p><p><img src="img/[email protected]" alt="QQ20200303-162428@2x"></p><p>这部分主要是Java在迭代过程中,一些拓展的功能。</p><p>比如:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>{</span><br><span class="line"> ZipInfo zipInfo = <span class="keyword">new</span> ZipInfo();</span><br><span class="line"> System.out.println(zipInfo.getClass().getClassLoader());</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p></p><p><code>ZipInfo</code>是<code>$JAVA_HOME/jre/lib/ext/zipfs.jar</code>包里的一个类,程序运行结果如下:</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">sun.misc.Launcher$ExtClassLoader@5e2de80c</span><br></pre></td></tr></table></figure><p></p><h4 id="应用程序类加载器"><a href="#应用程序类加载器" class="headerlink" title="应用程序类加载器"></a>应用程序类加载器</h4><p>应用程序类加载器AppClassLoader是虚拟机自带的加载器,用于加载当前应用的classpath的所有类,也就是我们自己写的那些Java代码,比如:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>{</span><br><span class="line"> System.out.println(Test.class.getClassLoader());</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p></p><p>程序运行结果:</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">sun.misc.Launcher$AppClassLoader@18b4aac2</span><br></pre></td></tr></table></figure><p></p><h4 id="用户自定义加载器"><a href="#用户自定义加载器" class="headerlink" title="用户自定义加载器"></a>用户自定义加载器</h4><p>除了使用上面三种JVM自带的类加载器外,我们也可以通过继承Java.lang.ClassLoader抽象类自定义一个类加载器。</p><p>这四种类加载器的关系如下图所示:</p><p><img src="img/[email protected]" alt="QQ20200303-165603@2x"></p><p>它们的关系是一种父子关系,我们可以通过代码验证:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>{</span><br><span class="line"> Class<Test> testClass = Test.class;</span><br><span class="line"> System.out.println(testClass.getClassLoader());</span><br><span class="line"> System.out.println(testClass.getClassLoader().getParent());</span><br><span class="line"> System.out.println(testClass.getClassLoader().getParent().getParent());</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>程序运行结果如下所示:</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">sun.misc.Launcher$AppClassLoader@18b4aac2</span><br><span class="line">sun.misc.Launcher$ExtClassLoader@61bbe9ba</span><br><span class="line">null</span><br></pre></td></tr></table></figure><p></p><h3 id="类加载步骤"><a href="#类加载步骤" class="headerlink" title="类加载步骤"></a>类加载步骤</h3><p>类的加载过程分为<strong>三个</strong>步骤:</p><h4 id="加载Loading"><a href="#加载Loading" class="headerlink" title="加载Loading"></a>加载Loading</h4><p>通过一个类的全类名获取其二进制字节流,将这个二进制流代表的静态存储结构转化为方法区的运行时数据结构,然后在内存中生成一个代表这个类的java.lang.Class对象,作为方法区中这个类的各种数据的访问入口。</p><h4 id="链接Linking"><a href="#链接Linking" class="headerlink" title="链接Linking"></a>链接Linking</h4><p>该过程又可以分为三个阶段:<strong>验证Verfication</strong>,<strong>准备Preparation</strong>和<strong>解析Resolution</strong>)。</p><ul><li>验证阶段用于确保加载的Class文件的字节流包含的信息是否符合虚拟机要求,保证其正确性合法性;</li><li>准备阶段为类变量(static修饰的变量)分配内存并根据对象类型设置相应的默认初始值(比如int类型为0,Integer类型为null)。<span style="color:red">这里不包含常量,因为常量在编译的时候分配,准备阶段会显示初始化。</span>类的实例变量不会在这个阶段准备初始化。</li><li><p>解析阶段用于将符号引用转换为直接引用。</p><p>观察如下代码:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>{</span><br><span class="line"> String str = <span class="string">"hello"</span>;</span><br><span class="line"> System.out.println(str);</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>使用javap -v命令查看其字节码:</p><p><img src="img/[email protected]" alt="QQ20200615-171009@2x"></p><p>可以看到常量池中有许多符号引用(比如#2),解析阶段就是将其解析为直接引用(比如#2表示字符串常量hello)的过程。</p></li></ul><h4 id="初始化Initialization"><a href="#初始化Initialization" class="headerlink" title="初始化Initialization"></a>初始化Initialization</h4><ul><li><p>该阶段就是执行类的构造器方法<code><clinit>()</code>的过程 ;该方法并不是类的构造器,不需要我们自己定义,是javac编译器自动搜集类中的所有类变量的赋值动作和静态代码块中的语句合并而来;</p><p>创建一个简单的类,包含一个名为aaa的类变量:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{</span><br><span class="line"></span><br><span class="line"> <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> aaa = <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">static</span> {</span><br><span class="line"> aaa = <span class="number">200</span>;</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>{</span><br><span class="line"> System.out.println(Test.aaa);</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>然后通过IDEA的jclasslib插件查看该类的class文件对应的字节码:</p><p><img src="img/[email protected]" alt="QQ20200615-143009@2x"></p><p>可以看到上面所说的构造器方法<code><clinit>()</code>,指令的操作就是为所有类变量赋值以及静态代码块中的操作。换句话说,如果一个类不包含类变量和静态代码块,那么它的字节码中就不会有构造器方法<code><clinit>()</code>。</p></li><li><p>构造器方法中的指令按照语句在源代码中出现的顺序执行;</p><p>观察如下代码:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{</span><br><span class="line"></span><br><span class="line"> <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> aaa = <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">static</span> {</span><br><span class="line"> aaa = <span class="number">200</span>;</span><br><span class="line"> bbb = <span class="number">300</span>;</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> bbb = <span class="number">2</span>;</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>{</span><br><span class="line"> System.out.println(Test.bbb);</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>上面程序输出结果为2,因为构造器方法中的指令按照语句在源代码中出现的顺序执行,查看构造器方法<code><clinit>()</code>指令来证明这一点:</p><p><img src="img/[email protected]" alt="QQ20200615-143747@2x"></p><p>这里还有一个细节,就是为什么在静态代码块下面才定义的类变量bbb,在静态代码块中可以进行修改呢?这就是Linking阶段中准备阶段所做的事情,准备阶段为类变量(static修饰的变量)分配内存并根据对象类型设置相应的默认初始值。这个时候bbb已经被分配并赋予默认初始值了,所以static块中可以使用该变量(换句话说,实例变量不行)。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{</span><br><span class="line"></span><br><span class="line"> <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> aaa = <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">static</span> {</span><br><span class="line"> aaa = <span class="number">200</span>;</span><br><span class="line"> System.out.println(Test.bbb);</span><br><span class="line"> bbb = <span class="number">300</span>;</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> bbb = <span class="number">2</span>;</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>{</span><br><span class="line"> System.out.println(Test.bbb);</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>上面输出0 2。</p><p>下面代码直接编译失败:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{</span><br><span class="line"> <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> aaa = <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">static</span> {</span><br><span class="line"> aaa = <span class="number">200</span>;</span><br><span class="line"> System.out.println(Test.bbb);</span><br><span class="line"> bbb = <span class="number">300</span>;</span><br><span class="line"> ccc = <span class="number">400</span>;</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> bbb = <span class="number">2</span>;</span><br><span class="line"> <span class="keyword">private</span> <span class="keyword">int</span> ccc = <span class="number">3</span>;</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>{</span><br><span class="line"> System.out.println(Test.bbb);</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p><img src="img/[email protected]" alt="QQ20200615-144259@2x"></p><p>因为ccc还没分配初始化呢。</p></li><li><p>若该类包含父类,那么JVM会保证父类的<code><clinit>()</code>先执行完毕;</p></li><li><p>虚拟机会保证一个类的<code><clinit>()</code>方法在多线程下被同步加锁。</p><p>观察如下代码:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>{</span><br><span class="line"> Runnable r = () -> {</span><br><span class="line"> System.out.println(Thread.currentThread().getName() + <span class="string">"开始"</span>);</span><br><span class="line"> <span class="keyword">new</span> Hello();</span><br><span class="line"> System.out.println(Thread.currentThread().getName() + <span class="string">"结束"</span>);</span><br><span class="line"> };</span><br><span class="line"></span><br><span class="line"> <span class="keyword">new</span> Thread(r, <span class="string">"线程1"</span>).start();</span><br><span class="line"> <span class="keyword">new</span> Thread(r, <span class="string">"线程2"</span>).start();</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Hello</span> </span>{</span><br><span class="line"> <span class="keyword">static</span> {</span><br><span class="line"> <span class="keyword">if</span> (<span class="keyword">true</span>) {</span><br><span class="line"> System.out.println(Thread.currentThread().getName() + <span class="string">"初始化当前类"</span>);</span><br><span class="line"> <span class="keyword">while</span> (<span class="keyword">true</span>) {</span><br><span class="line"></span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>程序启动后,main线程启动两个子线程,控制台输出如下:</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">线程1开始</span><br><span class="line">线程2开始</span><br><span class="line">线程1初始化当前类</span><br></pre></td></tr></table></figure><p>然后程序block住,这说明了虚拟机会保证一个类的<code><clinit>()</code>方法在多线程下被同步加锁。</p></li></ul><h3 id="双亲委派机制"><a href="#双亲委派机制" class="headerlink" title="双亲委派机制"></a>双亲委派机制</h3><p>聊到类加载器不得不提的另一个话题就是<strong>双亲委派机制</strong>,在了解什么是双亲委派机制之前,我们先来看个例子:</p><p>在src/main/java目录下新建java.lang包,然后在该包下新建一个String类:</p><p><img src="img/[email protected]" alt="QQ20200303-170626@2x"></p><p>String类的代码如下所示:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> java.lang;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">String</span> </span>{</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>{</span><br><span class="line"> System.out.println(<span class="string">"helo"</span>);</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p></p><p>程序输出结果:</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">错误: 在类 java.lang.String 中找不到 main 方法, 请将 main 方法定义为:</span><br><span class="line"> public static void main(String[] args)</span><br><span class="line">否则 JavaFX 应用程序类必须扩展javafx.application.Application</span><br></pre></td></tr></table></figure><p></p><div class="note info">所谓的双亲委派机制就是:当一个类收到了类加载请求,他首先不会尝试自己去加载这个类,而是把这个请求委派给父类去完成,每一个层次类加载器都是如此。只有当父类加载器反馈自己无法完成这个请求的时候(在它的加载路径下没有找到所需加载的Class),子类加载器才会尝试自己去加载。</div><p>所以上面的例子中,AppClassLoader委派给它的父类ExtClassLoader去加载,ExtClassLoader又委托给它的父类BootstrapClassLoader去加载。BootstrapClassLoader从它的加载路径<code>$JAVA_HOME/jre/lib/rt.jar</code>下找到了<code>java.lang.String</code>类,即rt.jar包下的String类,而该类里并没有main方法,所以便抛出了如上异常。</p><div class="note info">采用双亲委派的一个好处是:就如上面所说,不管是哪个加载器加载这个类,最终都是委托给顶层的启动类加载器进行加载,这样就保证了使用不同的类加载器最终得到的都是同样一个String对象,所以我们自定义的Java类并不会污染JDK自带的那些类(即使全类名一样),这种保护机制也叫沙箱安全机制。</div><h2 id="程序计数器"><a href="#程序计数器" class="headerlink" title="程序计数器"></a>程序计数器</h2><p><strong>程序计数器</strong>(Program Counter Register)又叫PC寄存器。每个线程都有一个程序计数器,是线程私有的。它是一个指针,指向方法区中的方法字节码,用来存储指向下一条指令的地址,也即将要执行的指令代码,由执行引擎读取下一条指令,是一个非常小的内存空间,几乎可以忽略不记。</p><p><img src="img/[email protected]" alt="QQ20200615-183140@2x"></p><p>如果执行的是一个Native方法,那这个计数器的值为undefied。</p><p>为什么需要程序计数器呢?因为CPU需要不停地切换各个线程,有了程序计数器后,当CPU切换回来后,我们就可以知道接着从哪开始继续执行程序,举个例子,现有如下代码:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>{</span><br><span class="line"> <span class="keyword">int</span> a = <span class="number">1</span>;</span><br><span class="line"> <span class="keyword">int</span> b = <span class="number">2</span>;</span><br><span class="line"> <span class="keyword">int</span> c = a + b;</span><br><span class="line"> System.out.println(c);</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p></p><p>查看其字节码:</p><p><img src="img/[email protected]" alt="QQ20200615-184326@2x"></p><p>假如当前线程的程序计数器存储的指令地址为6,这时候CPU切换到别的线程中处理工作;一段时间后,当前线程重新获取了CPU时间片继续执行时,根据程序计数器存的6就知道,当前需要执行iadd(即a+b操作)指令。执行引擎会将这条指令翻译为机器指令,然后CPU执行该运算操作。</p><h2 id="虚拟机栈(Java栈)"><a href="#虚拟机栈(Java栈)" class="headerlink" title="虚拟机栈(Java栈)"></a>虚拟机栈(Java栈)</h2><p>虚拟机栈也称为Java栈,每个线程在创建的时候都会创建一个虚拟机栈,其内部保存一个个栈帧(Stack Frame),对应着一次次的Java方法调用。和PC寄存器一样,虚拟机栈的生命周期和线程一致。虚拟机栈主管Java程序的运行,它保存方法的局部变量(8种基本数据类型,对象引用地址)、部分结果,并参与方法的调用和返回。</p><p>虚拟机栈示意图如下所示:</p><p><img src="img/[email protected]" alt="QQ20200618-091650@2x"></p><p>JVM对虚拟机栈的操作只有压栈(入栈)和出栈操作,遵循FILO原则;在一个活动线程中,一个时间点只会有一个活动的栈帧,即当前正在执行方法对应的栈帧(当前栈帧);如果一个方法调用了另一个方法,那么对应的新的栈帧将会被创建出来,放在栈顶,成为新的当前栈帧。</p><p>编写一个简单代码,使用debug的方式来观察入栈和出栈操作:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>{</span><br><span class="line"> <span class="keyword">new</span> Test().method1();</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">method1</span><span class="params">()</span> </span>{</span><br><span class="line"> System.out.println(<span class="string">"method1 start"</span>);</span><br><span class="line"> method2();</span><br><span class="line"> System.out.println(<span class="string">"method1 finish"</span>);</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">method2</span><span class="params">()</span> </span>{</span><br><span class="line"> System.out.println(<span class="string">"method2 start"</span>);</span><br><span class="line"> method3();</span><br><span class="line"> System.out.println(<span class="string">"method2 finish"</span>);</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">method3</span><span class="params">()</span> </span>{</span><br><span class="line"> System.out.println(<span class="string">"method3 start"</span>);</span><br><span class="line"> method4();</span><br><span class="line"> System.out.println(<span class="string">"method3 finish"</span>);</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">method4</span><span class="params">()</span> </span>{</span><br><span class="line"> System.out.println(<span class="string">"method4 start"</span>);</span><br><span class="line"> System.out.println(<span class="string">"method4 finish"</span>);</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p></p><p><img src="img/2020-06-18 09.33.53.gif" alt="2020-06-18 09.33.53.gif"></p><p>可以看到,执行main方法后,main方法首先入栈,接着调用method1方法,method1方法入栈;method1调用method2,method2入栈;method2调用method3,method3入栈;method3调用method4,method4入栈;method4执行结束,正常退出,method4出栈;method4出栈后,当前栈帧变为method3对应的栈帧;method3执行结束正常退出,method3出栈……以此类推,最终main方法执行结束出栈,程序结束。</p><p><strong>Java方法执行结束正常退出和抛出异常这两种情况会导致栈帧被弹出(退出)</strong>。</p><h3 id="虚拟机栈大小调整"><a href="#虚拟机栈大小调整" class="headerlink" title="虚拟机栈大小调整"></a>虚拟机栈大小调整</h3><p>Java虚拟机规范允许虚拟机栈的大小固定不变或者动态扩展。</p><ul><li>固定情况下:如果线程请求分配的栈容量超过Java虚拟机允许的最大容量,则抛出<span style="color:red">StackOverflowError</span>异常;</li><li>可动态扩展情况下:尝试扩展的时候无法申请到足够的内存;或者在创建新的线程的时候没有足够的内存去创建对应的虚拟机栈,则会抛出<span style="color:red">OutOfMemoryError</span>异常。</li></ul><p>不同平台的虚拟机栈默认大小不同:</p><ul><li><p>Linux/x64 (64-bit): 1024 KB</p></li><li><p>macOS (64-bit): 1024 KB</p></li><li><p>Oracle Solaris/x64 (64-bit): 1024 KB</p></li><li><p>Windows: 默认值取决于虚拟内存。</p></li></ul><p>我们可以通过<code>-Xss</code>(<code>-XX:ThreadStackSize</code>简写)设置虚拟机栈大小,默认单位为字节。也可以通过k或者K指定单位为KB,m或M指定单位为MB,g或G指定单位为GB。下面这组配置都是将虚拟机栈大小设置为1024KB:</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">-Xss1m</span><br><span class="line">-Xss1024k</span><br><span class="line">-Xss1048576</span><br></pre></td></tr></table></figure><p></p><p>虚拟机栈越大,方法调用深度越深,举个例子:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{</span><br><span class="line"> <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> count = <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>{</span><br><span class="line"> System.out.println(count);</span><br><span class="line"> count++;</span><br><span class="line"> main(args);</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p></p><p>在macOS平台下,虚拟机栈的默认大小为1024KB,程序运行结果如下:</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">......</span><br><span class="line">10817</span><br><span class="line">10818</span><br><span class="line">10819</span><br><span class="line">10820</span><br><span class="line">10821</span><br><span class="line">10822</span><br><span class="line">10823</span><br><span class="line">10824</span><br><span class="line">*** java.lang.instrument ASSERTION FAILED ***: "!errorOutstanding" with message transform method call failed at JPLISAgent.c line: 844</span><br><span class="line">Exception in thread "main" java.lang.StackOverflowError</span><br></pre></td></tr></table></figure><p></p><p>程序输出10824后抛出StackOverflowError;</p><p>我们通过<code>-Xss200k</code>命令将虚拟机栈大小调整为200KB再观察输出结果:</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">......</span><br><span class="line">1214</span><br><span class="line">1215</span><br><span class="line">1216</span><br><span class="line">1217</span><br><span class="line">1218</span><br><span class="line">1219</span><br><span class="line">*** java.lang.instrument ASSERTION FAILED ***: "!errorOutstanding" with message transform method call failed at JPLISAgent.c line: 844</span><br><span class="line">*** java.lang.instrument ASSERTION FAILED ***: "!errorOutstanding" with message transform method call failed at JPLISAgent.c line: 844</span><br><span class="line">*** java.lang.instrument ASSERTION FAILED ***: "!errorOutstanding" with message transform method call failed at JPLISAgent.c line: 844</span><br><span class="line">Exception in thread "main" java.lang.StackOverflowError</span><br></pre></td></tr></table></figure><p>可以看到,方法调用深度明显变小了。</p><h3 id="栈帧内部结构"><a href="#栈帧内部结构" class="headerlink" title="栈帧内部结构"></a>栈帧内部结构</h3><p>每个栈帧包含5个组成部分:局部变量表(Local Variables)、操作数栈(Operand Stack)、动态链接(Dynamic Linking)、方法返回地址(Return Address)和一些附加信息:</p><p><img src="img/[email protected]" alt="QQ20200618-140408@2x"></p><h4 id="局部变量表"><a href="#局部变量表" class="headerlink" title="局部变量表"></a>局部变量表</h4><p>局部变量表是一个数字数组,用于存储方法参数和方法体内的局部变量。</p><p>下面Test类包含hello静态方法:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">hello</span><span class="params">(String name)</span> </span>{</span><br><span class="line"> Date date = <span class="keyword">new</span> Date();</span><br><span class="line"> <span class="keyword">int</span> count = <span class="number">1</span>;</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p></p><p>使用<code>javap -v</code>命令查看其字节码:</p><p><img src="img/[email protected]" alt="QQ20200618-143216@2x"></p><p>非静态方法的局部变量表和静态方法相比,多了个this对象(即当前类):</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">halo</span><span class="params">(String name)</span> </span>{</span><br><span class="line"> Date date = <span class="keyword">new</span> Date();</span><br><span class="line"> <span class="keyword">int</span> count = <span class="number">1</span>;</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p></p><p><img src="img/[email protected]" alt="QQ20200618-143527@2x"></p><p>可以看到,非静态方法的局部变量表首位就存放了this对象,这也是静态方法内无法使用this的原因(因为静态方法的局部变量表中没有this对象)。</p><p>局部变量表数组容量的大小在编译期就可以唯一确定下来,并保存在方法的Code属性的maximum locacl variables数据项中,就拿上面Test类的hello方法来说,其字节码里已经指明了局部变量表的大小:</p><p><img src="img/[email protected]" alt="QQ20200618-145018@2x"></p><p>通过jclasslib插件也可以看到局部变量表的大小:</p><p><img src="img/[email protected]" alt="QQ20200618-145126@2x"></p><p>局部变量表的最基本单元是变量槽(Slot)。局部变量表中32位以内的数据类型(除long和double外)只占用一个slot,64位类型(long和double)占用两个slot。举个例子:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">hello</span><span class="params">(String name)</span> </span>{</span><br><span class="line"> Date date = <span class="keyword">new</span> Date();</span><br><span class="line"> <span class="keyword">long</span> number = <span class="number">200L</span>;</span><br><span class="line"> <span class="keyword">double</span> salary = <span class="number">6000.0</span>;</span><br><span class="line"> <span class="keyword">int</span> count = <span class="number">1</span>;</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p></p><p><img src="img/[email protected]" alt="QQ20200618-150204@2x"></p><p>此外,通过局部变量表包含的信息,我们还可以得出局部变量的作用范围。举个例子,当前有如下代码:</p><p><img src="img/[email protected]" alt="QQ20200618-150846@2x"></p><p>查看其字节码:</p><p><img src="img/[email protected]" alt="QQ20200618-151022@2x"></p><p>以方法参数name为例,查看LocalVariableTable,name参数对应的Start列的值为0,表示其在第0行字节码指令处生效(通过LineNumberTable我们可以知道,第0行字节码指令对应程序中的第6行代码);Length列的值为3,说明name参数的有效作用域长度为3,因为name是在第0行字节码指令处生效的,所以name在0 ~ 2行字节码指令范围内有效(通过LineNumberTable的对应关系,我们也可以知道name在我们的代码中作用域范围为第6行到第7行)。</p><p>局部变量表的槽位是可以重复利用的,如果一个局部变量过了其作用域,那么在其作用域之后申明的新的局部变量很有可能会复用过期局部变量的槽位。举个例子,现有如下代码:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">hello</span><span class="params">(String name)</span> </span>{</span><br><span class="line"> {</span><br><span class="line"> <span class="keyword">int</span> a = <span class="number">1</span>;</span><br><span class="line"> System.out.println(a);</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">int</span> b = <span class="number">2</span>;</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>查看其局部变量表:</p><p><img src="img/[email protected]" alt="QQ20200618-160223@2x"></p><p>可以看到局部变量a和b的槽位都是1,说明槽位重复利用了。这是因为在定义局部变量b的时候,局部变量a已经出了作用域失效销毁了,但是局部变量表的槽位已经开辟了,所以局部变量b直接重复利用索引为1的槽位。</p><h4 id="操作数栈"><a href="#操作数栈" class="headerlink" title="操作数栈"></a>操作数栈</h4><p>每一个独立的栈帧中除了包含局部变量表外,还包含一个FILO的操作数栈,用于保存计算过程中的中间结果,同时作为计算过程中变量临时的存储空间。每个操作数栈都有一个明确的深度,在编译期已经确定下来:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">add</span><span class="params">()</span> </span>{</span><br><span class="line"> <span class="keyword">int</span> a = <span class="number">1</span>;</span><br><span class="line"> <span class="keyword">int</span> b = <span class="number">1</span>;</span><br><span class="line"> <span class="keyword">int</span> c = a + b;</span><br><span class="line"> <span class="keyword">return</span> c;</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>查看其字节码:</p><p><img src="img/[email protected]" alt="QQ20200618-165953@2x"></p><p>栈中的任何一个元素都可以是任意的Java数据类型,32bit的类型占用一个栈深度,64bit的类型占用两个栈单位深度:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test</span><span class="params">()</span> </span>{</span><br><span class="line"> <span class="keyword">int</span> a = <span class="number">1</span>;</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p></p><p>查看其字节码:</p><p><img src="img/[email protected]" alt="QQ20200619-092727@2x"></p><p>操作数栈深度为1。</p><p>将代码的局部变量a类型改为64bit的double类型:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test</span><span class="params">()</span> </span>{</span><br><span class="line"> <span class="keyword">double</span> b = <span class="number">1.0</span>;</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p></p><p><img src="img/[email protected]" alt="QQ20200619-093123@2x"></p><p>操作数栈深度为2。</p><p>操作数栈在方法的执行过程中,根据字节码指令往栈中写入数据或提取数据,即入栈和出栈操作。虽然栈是用数组实现的,但根据栈的特性,对栈中数据访问不能通过索引,而是只能通过标准的入栈和出栈操作来完成一次数据访问。</p><p>下面通过一个例子来感受PC寄存器,局部变量表和操作数栈是如何相互配合完成一次方法的执行,代码如下所示:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">add</span><span class="params">()</span> </span>{</span><br><span class="line"> <span class="keyword">int</span> a = <span class="number">15</span>;</span><br><span class="line"> <span class="keyword">int</span> b = <span class="number">1</span>;</span><br><span class="line"> <span class="keyword">int</span> c = a + b;</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p></p><p>在查看字节码指令之前,先记录下几个入栈出栈的字节码指令含义:</p><ul><li>当int取值 -1 ~ 5 采用iconst指令入栈;</li><li>取值 -128 ~ 127(byte有效范围)采用bipush指令入栈;</li><li>取值 -32768 ~ 32767(short有效范围)采用sipush指令入栈;</li><li>取值 -2147483648 ~ 2147483647(int有效范围)采用ldc指令入栈;</li><li>istore,栈顶元素出栈,保存到局部变量表中;</li><li>iload,从局部变量表中加载数据入栈。</li></ul><p>更多字节码指令含义后续深入学习Java虚拟机字节码指令再说🌚。</p><p>上面方法对应的字节码如下:</p><p><img src="img/[email protected]" alt="QQ20200619-100036@2x"></p><p>指令执行过程中,PC寄存器,局部变量表和操作数栈状态如下图所示:</p><p><img src="img/[email protected]" alt="QQ20200619-102230@2x"></p><p><img src="img/[email protected]" alt="QQ20200619-102507@2x"></p><p><img src="img/[email protected]" alt="QQ20200619-102909@2x"></p><p><img src="img/[email protected]" alt="QQ20200619-103226@2x"></p><p><img src="img/[email protected]" alt="QQ20200619-103556@2x"></p><p><img src="img/[email protected]" alt="QQ20200619-103957@2x"></p><p><img src="img/[email protected]" alt="QQ20200619-104225@2x"></p><p><img src="img/[email protected]" alt="QQ20200619-104405@2x"></p><p>如果被调用的方法带有返回值的话,其返回值会被压入当前栈帧的操作数栈中。</p><h4 id="动态链接"><a href="#动态链接" class="headerlink" title="动态链接"></a>动态链接</h4><p>在Java源文件被编译成字节码文件时,所有的变量和方法引用都作为符号引用保存在class文件的常量池里,动态链接的作用就是为了将这些符号引用转换为调用方法的直接引用,比如:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">hello</span><span class="params">()</span> </span>{</span><br><span class="line"> System.out.println(<span class="string">"hello"</span>);</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p></p><p>其字节码中的常量池如下:</p><p><img src="img/[email protected]" alt="QQ20200619-141303@2x"></p><p>比如符号#27就表示为一个打印流。</p><h4 id="方法返回地址"><a href="#方法返回地址" class="headerlink" title="方法返回地址"></a>方法返回地址</h4><p>存放调用该方法的pc寄存器的值。一个方法的结束分为以下两种方式:</p><ul><li>正常执行结束;</li><li>出现未处理异常,非正常退出。</li></ul><p>无论是哪种方式退出,在方法退出后都返回到该方法被调用的位置。方法正常退出时,调用者的pc寄存器的值作为返回地址,即调用该方法的指令的下一条指令地址;异常退出时,返回地址需要通过异常表来确定。</p><h4 id="一些附加信息"><a href="#一些附加信息" class="headerlink" title="一些附加信息"></a>一些附加信息</h4><p>比如对程序调式提供的支持信息。</p><h2 id="本地方法接口"><a href="#本地方法接口" class="headerlink" title="本地方法接口"></a>本地方法接口</h2><p>本地方法接口(Native Interface)的作用是融合不同的编程语言为Java所用,它的初衷是融合C/C++程序。Java诞生的时候是 C/C++横行的时候,要想立足,必须调用 C/C++程序,于是就在内存中专门开辟了一块区域处理标记为native的代码。</p><p>比如查看java.lang.Thread类源码就会发现当中存在许多native方法:</p><p><img src="img/[email protected]" alt="QQ20200623-164809@2x"></p><p>native方法没有方法体(因为不是Java实现),所以看上去像是“接口”一样,故得名本地方法接口。</p><h2 id="本地方法栈"><a href="#本地方法栈" class="headerlink" title="本地方法栈"></a>本地方法栈</h2><p>如前所述,虚拟机栈用于管理Java方法的调用,而本地方法栈则是用于管理本地方法的调用。</p><h2 id="堆(Heap)"><a href="#堆(Heap)" class="headerlink" title="堆(Heap)"></a>堆(Heap)</h2><p>堆(Heap)一个JVM实例只存在一个堆内存,堆内存的大小是可以调节的。堆中保存着所有引用类型的真实信息,以方便执行器执行。堆在逻辑上分为三个区域:</p><p>Java7:</p><p><img src="img/[email protected]" alt="QQ20200305-103335@2x"></p><p>Java8:</p><p><img src="img/[email protected]" alt="QQ20200305-103619@2x"></p><p>可以看到,在Java7时代,堆分为新生区(新生区包含伊甸园区和幸存区,幸存区又包含幸存者0区和幸存者1区。此外,幸存者0区又称为From区,幸存者1区又称为To区,From区和To区并不是固定的,复制之后交互,谁空谁是To),养老区和永久代;在Java8中,永久代已经被移除,被一个称为元空间的区域所取代。元空间的本质和永久代类似。</p><p>元空间与永久代之间最大的区别在于:永久代使用的JVM的堆内存,但是java8以后的元空间并不在虚拟机中而是使用本机物理内存(所以在上图中,我用虚线表示)。</p><div class="note info">堆之所以要分区是因为:Java程序中不同对象的生命周期不同,70%~99%对象都是临时对象,这类对象在新生区“朝生夕死”。如果没有分区,GC时搜集垃圾需要对整个堆内存进行扫描;分区后,回收这些“朝生夕死”的对象,只需要在小范围的区域中(新生区)搜集垃圾。所以,分区的唯一理由就是为了优化GC性能。</div><h3 id="堆空间对象分配过程"><a href="#堆空间对象分配过程" class="headerlink" title="堆空间对象分配过程"></a>堆空间对象分配过程</h3><p>下面通过一个例子来讲述这几个区的交互逻辑:</p><p><strong>1.几乎任何新的对象都是在伊甸园区被new出来创建,刚开始的时候两个幸存者区和养老区都是空的:</strong></p><p><img src="img/QQ20200305-105423@2x_meitu_1.jpg" alt="QQ20200305-105423@2x"></p><p><strong>2.随着对象的不断创建,伊甸园区空间逐渐被填满:</strong></p><p><img src="img/QQ20200305-110220@2x_meitu_2.jpg" alt="QQ20200305-110220@2x_meitu_2.jpg"></p><p><strong>3.这时候将触发一次Minor GC(Young GC),删除未引用的对象,GC剩下来的还存在引用的对象将移动到幸存者0区,然后清空伊甸园区:</strong></p><p><img src="img/[email protected]" alt="QQ20200305-110720@2x"></p><p><strong>4.随着对象的创建,伊甸园区空间又满了,再一次触发Minor GC,删除未引用的对象,留下存在引用的对象。这次和上一次Minor GC有些不同,这轮GC留下的对象将被移动到幸存者1区,并且上一轮GC留下来的存储在幸存者0区的对象年龄递增并移动到幸存者1区。当所有幸存对象都移动到幸存者1区后,幸存者0区和伊甸园区空间清除:</strong></p><p><img src="img/[email protected]" alt="QQ20200305-111503@2x"></p><p><strong>5.随着对象的创建伊甸园区空间再一次满了,触发了第三次Minor GC,这一次幸存区空间将发生互换,GC留下来的幸存者将移动到幸存者0区,幸存者1区的幸存对象年龄递增后也移动到幸存者0区,然后伊甸园区和幸存者1区的空间被清除:</strong></p><p><img src="img/[email protected]" alt="QQ20200305-112210@2x"></p><p><strong>6.随着Minor GC的不断发生,幸存对象在两个幸存区不断地交换存储,年龄也不断递增。如此反反复复之后,当幸存对象的年龄达到指定的阈值(这个例子中是8,由JVM参数MaxTenuringThreshold决定)后,它们将被移动到养老区:</strong></p><p><img src="img/[email protected]" alt="QQ20200305-112448@2x"></p><p><strong>7.随着上述过程的不断出现,当养老区快满时,将触发Major GC(Full GC)进行养老区的内存清理。若养老区执行了GC之后发现依然无法进行对象的保存,就会产生OOM异常。</strong></p><p>一个对象被放置到养老区除了它的年龄达到阈值外,以下几种情况也会使得该对象直接被放置到养老区:</p><ol><li>对象创建后,无法放置到伊甸园区(比如伊甸园区的大小为10m,新的对象大小为11m,伊甸园区不够放,触发YGC。YGC后伊甸园区被清空,但还是无法容下11m的“超大对象”,所以直接放置到养老区。当然如果养老区放置不下则会触发FGC,FGC后还放不下则OOM);</li><li>YGC后,对象无法放置到幸存者To区也会直接晋升到养老区;</li><li>如果幸存区中相同年龄的所有对象大小大于幸存区空间的一半,年龄大于或等于这些对象年龄的对象可以直接进入养老区,无需等到年龄阈值。</li></ol><h3 id="堆参数"><a href="#堆参数" class="headerlink" title="堆参数"></a>堆参数</h3><p>以JDK1.8+HotSpot为例,常用的可调整的堆参数有:</p><table><tr><th>参数</th><th>含义</th></tr><tr><td>-Xms,等价于-XX:InitialHeapSize</td><td>设置堆的初始内存大小,默认为物理内存的1/64</td></tr><tr><td>-Xmx,等价于-XX:MaxHeapSize</td><td>设置堆的最大内存大小,默认为物理内存的1/4</td></tr><tr><td>-XX:Newratio</td><td>设置新生区和养老区的比例,比如值为2(默认值),则养老区是新生区的2倍,即养老区占据堆内存的2/3</td></tr><tr><td>-XX:Surviorratio</td><td>设置伊甸园区和一个幸存区的比例,比如值为8(默认值)则表示伊甸园区占新生区的8/10(两个幸存区是一样大的,8:1:1); 如果设置为5,则比例为5:1:1,即伊甸园区占新生区5/7</td></tr><tr><td>-Xmn</td><td>设置堆新生区的内存大小(一般不使用)</td></tr><tr><td>-XX:MaxTenuringThreshold</td><td>设置转入养老区的存活次数,默认值为15</td></tr><tr><td>-XX:+PrintFlagsInitial</td><td>查看所有参数的默认初始值</td></tr><tr><td>-XX:+PrintFlagsFinal</td><td>查看所有参数的最终值(被我们修改后的值不再是默认初始值)</td></tr></table><p>剩下所有可用参数可以查看oracle官方文档:<a href="https://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html" target="_blank" rel="noopener">https://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html</a>。</p><p><strong>生产环境中,推荐将-Xms和-Xmx设置为一样大,因为这样做的话在Java垃圾回收清理完堆区后不需要重新计算堆区大小,从而提高性能</strong>。此外,要在程序中输出详细的GC处理日志,可以使用<code>-XX:+PrintGCDetails</code>。</p><p>比如,我的电脑内存为32GB,所以堆的默认初始值大小为500MB左右,堆的最大值大约为8000MB左右:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>{</span><br><span class="line"> <span class="keyword">long</span> maxMemory = Runtime.getRuntime().maxMemory();</span><br><span class="line"> <span class="keyword">long</span> totalMemory = Runtime.getRuntime().totalMemory();</span><br><span class="line"></span><br><span class="line"> System.out.println(<span class="string">"堆内存的初始值"</span> + totalMemory / <span class="number">1024</span> / <span class="number">1024</span> + <span class="string">"mb"</span>);</span><br><span class="line"> System.out.println(<span class="string">"堆内存的最大值"</span> + maxMemory / <span class="number">1024</span> / <span class="number">1024</span> + <span class="string">"mb"</span>);</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p></p><p>程序输出:</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">堆内存的初始值491mb</span><br><span class="line">堆内存的最大值7282mb</span><br></pre></td></tr></table></figure><p></p><p>可以通过IDEA调整堆的大小:</p><p><img src="img/[email protected]" alt="QQ20200305-142031@2x"></p><p>我们将堆内存的初始大小和最大值都设置为10mb,并且开启GC日志打印,重新运行下面这段程序:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>{</span><br><span class="line"> <span class="keyword">long</span> maxMemory = Runtime.getRuntime().maxMemory();</span><br><span class="line"> <span class="keyword">long</span> totalMemory = Runtime.getRuntime().totalMemory();</span><br><span class="line"></span><br><span class="line"> System.out.println(<span class="string">"堆内存的初始值"</span> + totalMemory / <span class="number">1024</span> + <span class="string">"kb"</span>);</span><br><span class="line"> System.out.println(<span class="string">"堆内存的最大值"</span> + maxMemory / <span class="number">1024</span> + <span class="string">"kb"</span>);</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p></p><p>输出如下所示:</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">堆内存的初始值9728kb</span><br><span class="line">堆内存的最大值9728kb</span><br><span class="line">Heap</span><br><span class="line"> PSYoungGen total 2560K, used 1388K [0x00000007bfd00000, 0x00000007c0000000, 0x00000007c0000000)</span><br><span class="line"> eden space 2048K, 67% used [0x00000007bfd00000,0x00000007bfe5b370,0x00000007bff00000)</span><br><span class="line"> from space 512K, 0% used [0x00000007bff80000,0x00000007bff80000,0x00000007c0000000)</span><br><span class="line"> to space 512K, 0% used [0x00000007bff00000,0x00000007bff00000,0x00000007bff80000)</span><br><span class="line"> ParOldGen total 7168K, used 0K [0x00000007bf600000, 0x00000007bfd00000, 0x00000007bfd00000)</span><br><span class="line"> object space 7168K, 0% used [0x00000007bf600000,0x00000007bf600000,0x00000007bfd00000)</span><br><span class="line"> Metaspace used 2947K, capacity 4496K, committed 4864K, reserved 1056768K</span><br><span class="line"> class space used 320K, capacity 388K, committed 512K, reserved 1048576K</span><br></pre></td></tr></table></figure><p></p><p>可以看到,PSYoungGen(新生区)的总内存大小为2560k,ParOldGen(养老区)的总内存大小为7168k,总和刚好是9728K,这也说明了:Java8后的堆物理上只分为新生区和养老区,Metaspace(元空间)不占用堆内存,而是直接使用物理内存。</p><div class="note danger">那为什么我们设置的堆内存大小是10m(10240kb),控制台输出却只有9728kb呢?从上面的例子我们知道,幸存者区分为0区和1区,根据复制算法的特点,这两个区同一时刻总有一个区是空的,所以控制台输出的内存计算方式为:<strong>2048K(eden space)+512K(from space or to space)+7168K(ParOldGen)=9728K</strong>。9728K再加一个幸存区的大小512K刚好是10240K。</div><p>再举个OOM的例子,使用刚刚<code>-Xms10m -Xmx10m -XX:+PrintGCDetails</code>的设置,运行下面这段程序:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>{</span><br><span class="line"> String value = <span class="string">"hello"</span>;</span><br><span class="line"> <span class="keyword">while</span> (<span class="keyword">true</span>) {</span><br><span class="line"> value += value + <span class="keyword">new</span> Random().nextInt(<span class="number">1000000000</span>) + <span class="keyword">new</span> Random().nextInt(<span class="number">1000000000</span>);</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p></p><p>输出如下:</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">[GC (Allocation Failure) [PSYoungGen: 1893K->491K(2560K)] 1893K->597K(9728K), 0.0007246 secs] [Times: user=0.01 sys=0.00, real=0.00 secs] </span><br><span class="line">[GC (Allocation Failure) [PSYoungGen: 2207K->496K(2560K)] 2313K->1153K(9728K), 0.0008383 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] </span><br><span class="line">[GC (Allocation Failure) [PSYoungGen: 2007K->496K(2560K)] 2664K->1897K(9728K), 0.0009456 secs] [Times: user=0.01 sys=0.00, real=0.01 secs] </span><br><span class="line">[GC (Allocation Failure) [PSYoungGen: 2021K->496K(2560K)] 4894K->4113K(9728K), 0.0010814 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] </span><br><span class="line">[GC (Allocation Failure) [PSYoungGen: 1359K->496K(2560K)] 6448K->5600K(9728K), 0.0015792 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] </span><br><span class="line">[GC (Allocation Failure) [PSYoungGen: 496K->496K(1536K)] 5600K->5600K(8704K), 0.0006416 secs] [Times: user=0.01 sys=0.00, real=0.00 secs] </span><br><span class="line">[Full GC (Allocation Failure) [PSYoungGen: 496K->0K(1536K)] [ParOldGen: 5104K->2585K(7168K)] 5600K->2585K(8704K), [Metaspace: 2982K->2982K(1056768K)], 0.0044783 secs] [Times: user=0.02 sys=0.00, real=0.01 secs] </span><br><span class="line">[GC (Allocation Failure) [PSYoungGen: 61K->192K(2048K)] 7061K->7192K(9216K), 0.0012566 secs] [Times: user=0.01 sys=0.00, real=0.00 secs] </span><br><span class="line">[Full GC (Ergonomics) [PSYoungGen: 192K->0K(2048K)] [ParOldGen: 7000K->1840K(7168K)] 7192K->1840K(9216K), [Metaspace: 3042K->3042K(1056768K)], 0.0072023 secs] [Times: user=0.02 sys=0.00, real=0.01 secs] </span><br><span class="line">[GC (Allocation Failure) [PSYoungGen: 65K->160K(2048K)] 6321K->6416K(9216K), 0.0022603 secs] [Times: user=0.02 sys=0.00, real=0.00 secs] </span><br><span class="line">[Full GC (Ergonomics) [PSYoungGen: 160K->0K(2048K)] [ParOldGen: 6256K->4785K(7168K)] 6416K->4785K(9216K), [Metaspace: 3076K->3076K(1056768K)], 0.0056740 secs] [Times: user=0.03 sys=0.00, real=0.01 secs] </span><br><span class="line">[GC (Allocation Failure) [PSYoungGen: 0K->0K(2048K)] 4785K->4785K(9216K), 0.0003871 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] </span><br><span class="line">[Full GC (Allocation Failure) [PSYoungGen: 0K->0K(2048K)] [ParOldGen: 4785K->4765K(7168K)] 4785K->4765K(9216K), [Metaspace: 3076K->3076K(1056768K)], 0.0049903 secs] [Times: user=0.02 sys=0.00, real=0.00 secs] </span><br><span class="line">Heap</span><br><span class="line"> PSYoungGen total 2048K, used 59K [0x00000007bfd00000, 0x00000007c0000000, 0x00000007c0000000)</span><br><span class="line"> eden space 1024K, 5% used [0x00000007bfd00000,0x00000007bfd0efb8,0x00000007bfe00000)</span><br><span class="line"> from space 1024K, 0% used [0x00000007bfe00000,0x00000007bfe00000,0x00000007bff00000)</span><br><span class="line"> to space 1024K, 0% used [0x00000007bff00000,0x00000007bff00000,0x00000007c0000000)</span><br><span class="line"> ParOldGen total 7168K, used 4765K [0x00000007bf600000, 0x00000007bfd00000, 0x00000007bfd00000)</span><br><span class="line"> object space 7168K, 66% used [0x00000007bf600000,0x00000007bfaa77b8,0x00000007bfd00000)</span><br><span class="line"> Metaspace used 3113K, capacity 4496K, committed 4864K, reserved 1056768K</span><br><span class="line"> class space used 339K, capacity 388K, committed 512K, reserved 1048576K</span><br><span class="line">Exception in thread "main" java.lang.OutOfMemoryError: Java heap space</span><br><span class="line"> at java.util.Arrays.copyOf(Arrays.java:3332)</span><br><span class="line"> at java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:124)</span><br><span class="line"> at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:674)</span><br><span class="line"> at java.lang.StringBuilder.append(StringBuilder.java:208)</span><br><span class="line"> at cc.mrbird.Test.main(Test.java:19)</span><br></pre></td></tr></table></figure><p></p><p>可以看到,经过数次的GC和Full GC后,堆内存还是无法腾出空间,最终抛出OOM错误。日志的含义如下图所示:</p><p>Young GC(Minor GC):</p><p><img src="img/[email protected]" alt="QQ20200305-145255@2x"></p><p>Full GC(Major GC):</p><p><img src="img/[email protected]" alt="QQ20200305-171134@2x"></p><h3 id="TLAB"><a href="#TLAB" class="headerlink" title="TLAB"></a>TLAB</h3><p>JVM对伊甸园区继续进行划分,为每个线程分配了一个私有缓存区域,这块区域就是TLAB(Thread Local Allocation Buffer)。多线程同时分配内存时,使用TLAB可以避免一系列非线程安全问题,同时还能够提升内存分配的吞吐量。尽管不是所有的对象实例都能够在TLAB中成功分配内存,但JVM确实是将TLAB作为内存分配的首选:</p><p><img src="img/[email protected]" alt="QQ20200629-142307@2x"></p><p><img src="img/[email protected]" alt="QQ20200630-112921@2x"></p><p>我们可以使用<code>-XX:UseTLAB</code>设置是否开启TLAB,举个例子:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>{</span><br><span class="line"> TimeUnit.SECONDS.sleep(<span class="number">100</span>);</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line">}</span><br></pre></td></tr></table></figure><p></p><p>运行main方法:</p><p><img src="img/[email protected]" alt="QQ20200629-141728@2x"></p><p>可以看到TLAB默认是开启的。</p><p>TLAB空间的内存非常小,仅占整个伊甸园区的1%,可以通过<code>-XX:TLABWasteTargetPercent</code>设置TLAB空间所占用伊甸园区空间的百分比。</p><p>有了TLAB的概念后,我们就不能说堆空间一定是线程共享的了。</p><h2 id="方法区"><a href="#方法区" class="headerlink" title="方法区"></a>方法区</h2><p><strong>方法区</strong>并不是所谓的<del>存储方法的区域</del>,而是供各线程共享的运行时内存区域。它存储了已被虚拟机加载的类型信息、常量、静态变量、即时编译器编译后的代码缓存等。</p><p>方法区也是<strong>一种规范</strong>,在不同虚拟机里头实现是不一样的,最典型的实现就是HotSpot虚拟机Java8之前的永久代(PermGen space)和Java8的元空间(Metaspace)。</p><h3 id="设置方法区大小"><a href="#设置方法区大小" class="headerlink" title="设置方法区大小"></a>设置方法区大小</h3><p>方法区的大小决定了系统可以加载多少个类,如果系统定义了太多的类,导致方法区溢出,虚拟机则会抛出<span style="color:red">java.lang.OutOfMemoryError: PermGen space</span>(Java 7)或者<span style="color:red">java.lang.OutOfMemoryError: Metaspace</span>(Java 8)内存溢出错误。</p><p>以Java8版本为例,我们可以使用<code>-XX:MetaspaceSize=size</code>设置元空间初始大小,<code>-XX:MaxMetaspaceSize=size</code>设置元空间最大值。默认情况下,在windows平台上,<code>-XX:MetaspaceSize</code>值为21M,<code>-XX:MaxMetaspaceSize</code>值为-1,即没有限制,所以极端情况下如果不断地加载类,虚拟机会耗尽所有可用的系统内存。</p><p>下面举个元空间OOM的例子:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.sun.org.apache.bcel.internal.util.ClassLoader;</span><br><span class="line"><span class="keyword">import</span> com.sun.xml.internal.ws.org.objectweb.asm.ClassWriter;</span><br><span class="line"><span class="keyword">import</span> jdk.internal.org.objectweb.asm.Opcodes;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> <span class="keyword">extends</span> <span class="title">ClassLoader</span> </span>{</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>{</span><br><span class="line"> <span class="keyword">int</span> count = <span class="number">0</span>;</span><br><span class="line"> <span class="keyword">try</span> {</span><br><span class="line"> Test test = <span class="keyword">new</span> Test();</span><br><span class="line"> <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i < <span class="number">10000</span>; i++) {</span><br><span class="line"> String className = <span class="string">"Class"</span> + i;</span><br><span class="line"> <span class="comment">// 创建ClassWriter对象,用于生成类的二进制字节码</span></span><br><span class="line"> ClassWriter classWriter = <span class="keyword">new</span> ClassWriter(<span class="number">0</span>);</span><br><span class="line"> <span class="comment">// 指定版本号、修饰符、类名、包名、父类和接口</span></span><br><span class="line"> classWriter.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, className, <span class="keyword">null</span>, <span class="string">"java/lang/Object"</span>, <span class="keyword">null</span>);</span><br><span class="line"> <span class="keyword">byte</span>[] bytes = classWriter.toByteArray();</span><br><span class="line"> <span class="comment">// 加载类</span></span><br><span class="line"> test.defineClass(className, bytes, <span class="number">0</span>, bytes.length);</span><br><span class="line"> count++;</span><br><span class="line"> }</span><br><span class="line"> } <span class="keyword">finally</span> {</span><br><span class="line"> System.out.println(count);</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p></p><p>上面例子中,我们尝试加载10000个类,通过参数<code>-XX:MetaspaceSize=10m -XX:MaxMetaspaceSize=10m</code>将元空间大小设置为固定大小10M,运行上面的程序控制台输出:</p><p><img src="img/[email protected]" alt="QQ20200630-110519@2x"></p><h3 id="方法区、堆、栈关系"><a href="#方法区、堆、栈关系" class="headerlink" title="方法区、堆、栈关系"></a>方法区、堆、栈关系</h3><p>方法区和堆、栈的关系如下图所示:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Bird</span> </span>{</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>{</span><br><span class="line"> Bird bird = <span class="keyword">new</span> Bird();</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p></p><p><img src="img/[email protected]" alt="QQ20200630-113730@2x"></p><p><img src="img/[email protected]" alt="QQ20200630-135333@2x"></p><h3 id="方法区内部结构"><a href="#方法区内部结构" class="headerlink" title="方法区内部结构"></a>方法区内部结构</h3><p>方法区内部主要存储了以下内容(不同JDK版本内容有所不同,具体参考下面“方法区演进”):</p><h4 id="类型信息"><a href="#类型信息" class="headerlink" title="类型信息"></a>类型信息</h4><p>对每个加载的类型(类class、接口 interface、枚举enum、注解 annotation),JVM必须在方法区中存储以下类型信息:</p><ol><li>这个类型的完整有效名称(包名.类名);</li><li>这个类型直接父类的完整有效名(interface和java.lang.Object没有父类);</li><li>这个类的修饰符(public,abstract,final);</li><li>这个类型直接接口的一个有序列表(一个类可以实现多个接口)。</li></ol><h4 id="方法信息"><a href="#方法信息" class="headerlink" title="方法信息"></a>方法信息</h4><p>方法信息包含了这个类的所有方法信息(包括构造器),这些信息和其声明顺序一致:</p><ol><li>方法名称;</li><li>方法的返回值类型(没有返回值则是void);</li><li>方法参数的数量和类型(有序);</li><li>方法的修饰符(public,private,protected,static,final,synchronized,native,abstract);</li><li>方法的字节码、操作数栈、局部变量表及其大小(abstract和native方法除外);</li><li>异常表(abstract和native方法除外)。</li></ol><h4 id="域信息"><a href="#域信息" class="headerlink" title="域信息"></a>域信息</h4><p>域Field我们也常称为属性,字段。域信息包含:</p><ol><li>域的声明顺序;</li><li>域的相关信息,包括名称、类型、修饰符(public,private,protected,static,final,volatile,transient)。</li></ol><h4 id="JIT代码缓存"><a href="#JIT代码缓存" class="headerlink" title="JIT代码缓存"></a>JIT代码缓存</h4><p>这部分在👇执行引擎中再做说明。</p><h4 id="运行时常量池"><a href="#运行时常量池" class="headerlink" title="运行时常量池"></a>运行时常量池</h4><p>在上面虚拟机栈的介绍中,我们知道类字节码反编译后,会有一个constant pool的结构,俗称为常量池,所有的变量和方法引用都作为符号引用保存在class文件的常量池里。虚拟机栈的动态链接就是将符号引用(这些符号引用的集合就是常量池)转换为直接引用(符号引用对应的具体信息,这些具体信息的集合就是运行时常量池,存在方法区中)的过程。</p><h4 id="静态变量"><a href="#静态变量" class="headerlink" title="静态变量"></a>静态变量</h4><p>静态变量就是使用static修饰的域信息。静态变量和类关联在一起,随着类的加载而加载,它们成为类数据在逻辑上的一部分。静态变量也成为类变量,类变量被类的所有实例共享,即使没有类实例时你也可以访问它:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{</span><br><span class="line"></span><br><span class="line"> <span class="keyword">private</span> <span class="keyword">static</span> String hello = <span class="string">"hello"</span>;</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">hello</span><span class="params">()</span> </span>{</span><br><span class="line"> System.out.println(<span class="string">"hello"</span>);</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>{</span><br><span class="line"> Test test = <span class="keyword">null</span>;</span><br><span class="line"> test.hello();</span><br><span class="line"> System.out.println(test.hello);</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p></p><p>上面程序运行并不会报空指针异常。</p><p>通过final修饰的静态变量我们俗称常量。常量在编译的时候就会被分配具体值:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{</span><br><span class="line"></span><br><span class="line"> <span class="keyword">private</span> <span class="keyword">static</span> String hello = <span class="string">"hello"</span>;</span><br><span class="line"> <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String HELLO = <span class="string">"hello"</span>;</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>通过<code>javap -v -p Test.class</code>查看其字节码:</p><p><img src="img/[email protected]" alt="QQ20200630-170711@2x"></p><p>通过上面的学习我们知道,静态变量(类变量)在类加载过程的初始化阶段才会被赋值。</p><h4 id="演示方法区内部结构"><a href="#演示方法区内部结构" class="headerlink" title="演示方法区内部结构"></a>演示方法区内部结构</h4><p>下面通过字节码内容来查看上面这些信息,现有如下代码:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> <span class="keyword">extends</span> <span class="title">Object</span> <span class="keyword">implements</span> <span class="title">Cloneable</span>, <span class="title">Serializable</span> </span>{</span><br><span class="line"></span><br><span class="line"> <span class="keyword">private</span> <span class="keyword">static</span> String hello = <span class="string">"hello"</span>;</span><br><span class="line"> <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String HELLO = <span class="string">"hello"</span>;</span><br><span class="line"> <span class="keyword">public</span> <span class="keyword">int</span> a = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">method1</span><span class="params">()</span> </span>{</span><br><span class="line"> System.out.println(<span class="string">"method1"</span>);</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title">method2</span><span class="params">(String name)</span> </span>{</span><br><span class="line"> <span class="keyword">try</span> {</span><br><span class="line"> <span class="keyword">int</span> a = <span class="number">1</span>;</span><br><span class="line"> <span class="keyword">int</span> b = a / <span class="number">0</span>;</span><br><span class="line"> } <span class="keyword">catch</span> (Exception e) {</span><br><span class="line"> e.printStackTrace();</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">return</span> name;</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><p>通过<code>javap -v -p Test.class</code>查看其字节码:</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br></pre></td><td class="code"><pre><span class="line">Classfile /Users/mrbird/idea workspace/JVM-Learn/target/classes/cc/mrbird/jvm/learn/Test.class</span><br><span class="line"> Last modified <span class="number">2019</span>-<span class="number">4</span>-<span class="number">01</span>; size <span class="number">1016</span> bytes</span><br><span class="line"> MD5 checksum ab0309674b0f0b5fbd0766af035efe0a</span><br><span class="line"> Compiled from <span class="string">"Test.java"</span></span><br><span class="line"><span class="comment">// 类型信息</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">cc</span>.<span class="title">mrbird</span>.<span class="title">jvm</span>.<span class="title">learn</span>.<span class="title">Test</span> <span class="keyword">implements</span> <span class="title">java</span>.<span class="title">lang</span>.<span class="title">Cloneable</span>,<span class="title">java</span>.<span class="title">io</span>.<span class="title">Serializable</span></span></span><br><span class="line"> minor version: 0</span><br><span class="line"> major version: <span class="number">52</span></span><br><span class="line"> <span class="comment">// 类的修饰符</span></span><br><span class="line"> flags: ACC_PUBLIC, ACC_SUPER</span><br><span class="line"><span class="comment">// 常量池</span></span><br><span class="line">Constant pool:</span><br><span class="line"> #1 = Methodref #11.#38 // java/lang/Object."<init>":()V</span><br><span class="line"> #2 = Fieldref #10.#39 // cc/mrbird/jvm/learn/Test.a:I</span><br><span class="line"> #3 = Fieldref #40.#41 // java/lang/System.out:Ljava/io/PrintStream;</span><br><span class="line"> #4 = String #27 // method1</span><br><span class="line"> #5 = Methodref #42.#43 // java/io/PrintStream.println:(Ljava/lang/String;)V</span><br><span class="line"> #6 = Class #44 // java/lang/Exception</span><br><span class="line"> #7 = Methodref #6.#45 // java/lang/Exception.printStackTrace:()V</span><br><span class="line"> #8 = String #14 // hello</span><br><span class="line"> #9 = Fieldref #10.#46 // cc/mrbird/jvm/learn/Test.hello:Ljava/lang/String;</span><br><span class="line"> #10 = Class #47 // cc/mrbird/jvm/learn/Test</span><br><span class="line"> #11 = Class #48 // java/lang/Object</span><br><span class="line"> #12 = Class #49 // java/lang/Cloneable</span><br><span class="line"> #13 = Class #50 // java/io/Serializable</span><br><span class="line"> #14 = Utf8 hello</span><br><span class="line"> #15 = Utf8 Ljava/lang/String;</span><br><span class="line"> #16 = Utf8 HELLO</span><br><span class="line"> #17 = Utf8 ConstantValue</span><br><span class="line"> #18 = Utf8 a</span><br><span class="line"> #19 = Utf8 I</span><br><span class="line"> #20 = Utf8 <init></span><br><span class="line"> #21 = Utf8 ()V</span><br><span class="line"> #22 = Utf8 Code</span><br><span class="line"> #23 = Utf8 LineNumberTable</span><br><span class="line"> #24 = Utf8 LocalVariableTable</span><br><span class="line"> #25 = Utf8 this</span><br><span class="line"> #26 = Utf8 Lcc/mrbird/jvm/learn/Test;</span><br><span class="line"> #27 = Utf8 method1</span><br><span class="line"> #28 = Utf8 method2</span><br><span class="line"> #29 = Utf8 (Ljava/lang/String;)Ljava/lang/String;</span><br><span class="line"> #30 = Utf8 e</span><br><span class="line"> #31 = Utf8 Ljava/lang/Exception;</span><br><span class="line"> #32 = Utf8 name</span><br><span class="line"> #33 = Utf8 StackMapTable</span><br><span class="line"> #34 = Class #44 // java/lang/Exception</span><br><span class="line"> #35 = Utf8 <clinit></span><br><span class="line"> #36 = Utf8 SourceFile</span><br><span class="line"> #37 = Utf8 Test.java</span><br><span class="line"> #38 = NameAndType #20:#21 // "<init>":()V</span><br><span class="line"> #39 = NameAndType #18:#19 // a:I</span><br><span class="line"> #40 = Class #51 // java/lang/System</span><br><span class="line"> #41 = NameAndType #52:#53 // out:Ljava/io/PrintStream;</span><br><span class="line"> #42 = Class #54 // java/io/PrintStream</span><br><span class="line"> #43 = NameAndType #55:#56 // println:(Ljava/lang/String;)V</span><br><span class="line"> #44 = Utf8 java/lang/Exception</span><br><span class="line"> #45 = NameAndType #57:#21 // printStackTrace:()V</span><br><span class="line"> #46 = NameAndType #14:#15 // hello:Ljava/lang/String;</span><br><span class="line"> #47 = Utf8 cc/mrbird/jvm/learn/Test</span><br><span class="line"> #48 = Utf8 java/lang/Object</span><br><span class="line"> #49 = Utf8 java/lang/Cloneable</span><br><span class="line"> #50 = Utf8 java/io/Serializable</span><br><span class="line"> #51 = Utf8 java/lang/System</span><br><span class="line"> #52 = Utf8 out</span><br><span class="line"> #53 = Utf8 Ljava/io/PrintStream;</span><br><span class="line"> #54 = Utf8 java/io/PrintStream</span><br><span class="line"> #55 = Utf8 println</span><br><span class="line"> #56 = Utf8 (Ljava/lang/String;)V</span><br><span class="line"> #57 = Utf8 printStackTrace</span><br><span class="line">{</span><br><span class="line"></span><br><span class="line"> <span class="comment">// 域信息</span></span><br><span class="line"> <span class="keyword">private</span> <span class="keyword">static</span> java.lang.String hello;</span><br><span class="line"> descriptor: Ljava/lang/String;</span><br><span class="line"> flags: ACC_PRIVATE, ACC_STATIC</span><br><span class="line"> <span class="comment">// 域信息</span></span><br><span class="line"> <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> java.lang.String HELLO;</span><br><span class="line"> descriptor: Ljava/lang/String;</span><br><span class="line"> flags: ACC_PRIVATE, ACC_STATIC, ACC_FINAL</span><br><span class="line"> ConstantValue: String hello</span><br><span class="line"> <span class="comment">// 域信息</span></span><br><span class="line"> <span class="keyword">public</span> <span class="keyword">int</span> a;</span><br><span class="line"> descriptor: I</span><br><span class="line"> flags: ACC_PUBLIC</span><br><span class="line"> <span class="comment">// 方法信息</span></span><br><span class="line"> <span class="keyword">public</span> cc.mrbird.jvm.learn.Test();</span><br><span class="line"> descriptor: ()V</span><br><span class="line"> flags: ACC_PUBLIC</span><br><span class="line"> Code:</span><br><span class="line"> stack=<span class="number">2</span>, locals=<span class="number">1</span>, args_size=<span class="number">1</span></span><br><span class="line"> <span class="number">0</span>: aload_0</span><br><span class="line"> 1: invokespecial #1 // Method java/lang/Object."<init>":()V</span><br><span class="line"> <span class="number">4</span>: aload_0</span><br><span class="line"> <span class="number">5</span>: iconst_0</span><br><span class="line"> 6: putfield #2 // Field a:I</span><br><span class="line"> <span class="number">9</span>: <span class="keyword">return</span></span><br><span class="line"> LineNumberTable:</span><br><span class="line"> line <span class="number">5</span>: <span class="number">0</span></span><br><span class="line"> line <span class="number">9</span>: <span class="number">4</span></span><br><span class="line"> LocalVariableTable:</span><br><span class="line"> Start Length Slot Name Signature</span><br><span class="line"> <span class="number">0</span> <span class="number">10</span> <span class="number">0</span> <span class="keyword">this</span> Lcc/mrbird/jvm/learn/Test;</span><br><span class="line"> <span class="comment">// 方法信息</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">method1</span><span class="params">()</span></span>;</span><br><span class="line"> descriptor: ()V</span><br><span class="line"> flags: ACC_PUBLIC</span><br><span class="line"> Code:</span><br><span class="line"> <span class="comment">// 操作数栈大小,局部变量表大小,参数个数</span></span><br><span class="line"> stack=<span class="number">2</span>, locals=<span class="number">1</span>, args_size=<span class="number">1</span></span><br><span class="line"> 0: getstatic #3 // Field java/lang/System.out:Ljava/io/PrintStream;</span><br><span class="line"> 3: ldc #4 // String method1</span><br><span class="line"> 5: invokevirtual #5 // Method java/io/PrintStream.println:(Ljava/lang/String;)V</span><br><span class="line"> <span class="number">8</span>: <span class="keyword">return</span></span><br><span class="line"> LineNumberTable:</span><br><span class="line"> line <span class="number">12</span>: <span class="number">0</span></span><br><span class="line"> line <span class="number">13</span>: <span class="number">8</span></span><br><span class="line"> LocalVariableTable:</span><br><span class="line"> Start Length Slot Name Signature</span><br><span class="line"> <span class="number">0</span> <span class="number">9</span> <span class="number">0</span> <span class="keyword">this</span> Lcc/mrbird/jvm/learn/Test;</span><br><span class="line"> <span class="comment">// 方法信息</span></span><br><span class="line"> <span class="keyword">public</span> <span class="keyword">static</span> java.lang.<span class="function">String <span class="title">method2</span><span class="params">(java.lang.String)</span></span>;</span><br><span class="line"> descriptor: (Ljava/lang/String;)Ljava/lang/String;</span><br><span class="line"> flags: ACC_PUBLIC, ACC_STATIC</span><br><span class="line"> Code:</span><br><span class="line"> stack=<span class="number">2</span>, locals=<span class="number">3</span>, args_size=<span class="number">1</span></span><br><span class="line"> <span class="number">0</span>: iconst_1</span><br><span class="line"> <span class="number">1</span>: istore_1</span><br><span class="line"> <span class="number">2</span>: iload_1</span><br><span class="line"> <span class="number">3</span>: iconst_0</span><br><span class="line"> <span class="number">4</span>: idiv</span><br><span class="line"> <span class="number">5</span>: istore_2</span><br><span class="line"> <span class="number">6</span>: goto <span class="number">14</span></span><br><span class="line"> <span class="number">9</span>: astore_1</span><br><span class="line"> <span class="number">10</span>: aload_1</span><br><span class="line"> 11: invokevirtual #7 // Method java/lang/Exception.printStackTrace:()V</span><br><span class="line"> <span class="number">14</span>: aload_0</span><br><span class="line"> <span class="number">15</span>: areturn</span><br><span class="line"> <span class="comment">// 异常表</span></span><br><span class="line"> Exception table:</span><br><span class="line"> from to target type</span><br><span class="line"> <span class="number">0</span> <span class="number">6</span> <span class="number">9</span> Class java/lang/Exception</span><br><span class="line"> LineNumberTable:</span><br><span class="line"> line <span class="number">17</span>: <span class="number">0</span></span><br><span class="line"> line <span class="number">18</span>: <span class="number">2</span></span><br><span class="line"> line <span class="number">21</span>: <span class="number">6</span></span><br><span class="line"> line <span class="number">19</span>: <span class="number">9</span></span><br><span class="line"> line <span class="number">20</span>: <span class="number">10</span></span><br><span class="line"> line <span class="number">22</span>: <span class="number">14</span></span><br><span class="line"> <span class="comment">// 局部变量表</span></span><br><span class="line"> LocalVariableTable:</span><br><span class="line"> Start Length Slot Name Signature</span><br><span class="line"> <span class="number">2</span> <span class="number">4</span> <span class="number">1</span> a I</span><br><span class="line"> <span class="number">10</span> <span class="number">4</span> <span class="number">1</span> e Ljava/lang/Exception;</span><br><span class="line"> <span class="number">0</span> <span class="number">16</span> <span class="number">0</span> name Ljava/lang/String;</span><br><span class="line"> StackMapTable: number_of_entries = <span class="number">2</span></span><br><span class="line"> frame_type = <span class="number">73</span> <span class="comment">/* same_locals_1_stack_item */</span></span><br><span class="line"> stack = [ class java/lang/Exception ]</span><br><span class="line"> frame_type = <span class="number">4</span> <span class="comment">/* same */</span></span><br><span class="line"></span><br><span class="line"> <span class="keyword">static</span> {};</span><br><span class="line"> descriptor: ()V</span><br><span class="line"> flags: ACC_STATIC</span><br><span class="line"> Code:</span><br><span class="line"> stack=<span class="number">1</span>, locals=<span class="number">0</span>, args_size=<span class="number">0</span></span><br><span class="line"> 0: ldc #8 // String hello</span><br><span class="line"> 2: putstatic #9 // Field hello:Ljava/lang/String;</span><br><span class="line"> <span class="number">5</span>: <span class="keyword">return</span></span><br><span class="line"> LineNumberTable:</span><br><span class="line"> line <span class="number">7</span>: <span class="number">0</span></span><br><span class="line">}</span><br><span class="line">SourceFile: <span class="string">"Test.java"</span></span><br></pre></td></tr></table></figure><p></p><h3 id="方法区的演进"><a href="#方法区的演进" class="headerlink" title="方法区的演进"></a>方法区的演进</h3><p>随着JDK的迭代升级,Hotspot中方法区的存储的内容发生了如下变化(上面介绍的方法区的内部结构是经典情况下的,具体还是需要看JDK是什么版本):</p><table><thead><tr><th>版本</th><th>描述</th></tr></thead><tbody><tr><td>jdk1.6及之前</td><td>有永久代(permanent generation),<strong>静态变量存放在永久代上</strong></td></tr><tr><td>jdk1.7</td><td>有永久代,但已经逐步“去永久代”,<strong>字符串常量池、静态变量移除,保存在堆中</strong></td></tr><tr><td>jdk1.8及之后</td><td>无永久代,类型信息、字段、方法、<strong>常量</strong>保存在<strong>本地内存的元空间</strong>,但<strong>字符串常量池、静态变量仍然保存在堆中</strong></td></tr></tbody></table><div class="note danger">上面说的静态变量在JDK1.6之前存放在永久代,JDK1.7后移动到堆空间指的是变量本身,变量对应的对象实例一直都是在堆空间分配的。举个例子:<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StaticObjTest</span> </span>{</span><br><span class="line"></span><br><span class="line"> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>{</span><br><span class="line"> <span class="keyword">static</span> ObjectHolder staticObj = <span class="keyword">new</span> ObjectHolder();</span><br><span class="line"> ObjectHolder instanceObj = <span class="keyword">new</span> ObjectHolder();</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">void</span> <span class="title">foo</span><span class="params">()</span> </span>{</span><br><span class="line"> ObjectHolder localObj = <span class="keyword">new</span> ObjectHolder();</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="keyword">private</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">ObjectHolder</span> </span>{</span><br><span class="line"></span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure>这个例子中,三个new ObjectHolder()的创建,都是在堆中分配的,localObj是方法foo内的局部变量,存放在虚拟机栈的局部变量表中;instanceObj为成员变量,随着对象实例的创建也分配在堆中;静态变量staticObj根据JDK版本的不同存放位置也不同,JDK1.6及之前,存放在永久代中,JDK1.7及之后存放到堆中。</div><p>永久代为什么会被元空间替代?因为永久代的大小是很难确定的,如果一个程序动态加载的类过多就很容易触发永久代的Full GC(Full GC代价大,耗时长,影响程序性能)甚至OOM,程序直接奔溃;而元空间和永久代之间最大的区别在于:元空间并不在虚拟机中,而是使用本地内存,这样元空间就基本不会因为触发Full GC和OOM了。</p><p>字符串常量池(StringTable)为什么要放到堆中?因为如果将StringTable放在永久代的话回收效率很低,在Full GC的时候才会触发。而Full GC是老年代的空间不足、永久代不足时才会触发。这就导致 StringTable回收效率不高。而我们开发中会有大量的字符串被创建,回收效率低,导致永久代内存不足。放到堆里,能及时回收内存。</p><h3 id="方法区垃圾回收"><a href="#方法区垃圾回收" class="headerlink" title="方法区垃圾回收"></a>方法区垃圾回收</h3><p>方法区也存在垃圾回收,方法区的垃圾收集主要回收两部分内容:常量池中废弃的常量和不再使用的类型。</p><h2 id="执行引擎"><a href="#执行引擎" class="headerlink" title="执行引擎"></a>执行引擎</h2><p>类加载器加载的字节码并不能够直接运行在操作系统之上,因为字节码指令不是本地机器指令,执行引擎(Execute Engine)的任务就是讲字节码指令解释为对应平台上的本地机器指令。通俗地讲,执行引擎就是将高级语言翻译为本地机器语言的翻译官。</p><h3 id="解释器和JIT编译器"><a href="#解释器和JIT编译器" class="headerlink" title="解释器和JIT编译器"></a>解释器和JIT编译器</h3><ul><li><p>解释器(Interpreter):JVM在程序运行时通过解释器逐行将字节码转为本地机器指令执行;</p></li><li><p>JIT编译器(Just In Time Compiler,即时编译器):解释器的优点是程序一启动就可以马上发挥作用,逐行翻译字节码执行程序。而对于一些高频的代码(如循环体内代码和高频调用方法等),如果每次执行都用解释器逐行将字节码翻译为机器指令的话,势必会造成浪费,所以我们可以通过即时编译器将这部分高频代码直接编译为机器指令然后缓存在方法区中(上面介绍方法区内部组成时提到过JIT代码缓存),以此提高执行效率。和解释器相比,即时编译器的缺点就是编译需要耗费一定时间。</p></li></ul><div class="note info">正因为JVM在执行Java代码的时候,通常会将解释执行和编译执行二者结合起来进行,所以Java也可以说是一种半编译半解释型语言。</div><h4 id="热点代码"><a href="#热点代码" class="headerlink" title="热点代码"></a>热点代码</h4><p>hotspot通过两种方式来确定当前代码是否为热点代码:</p><ul><li><p>方法调用计数器:统计方法调用的次数;</p></li><li><p>回边计数器:统计循环体执行的循环次数。</p></li></ul><p>当一个方法被调用时,会先检查该方法是否存在被JIT编译器编译过的版本,如果存在,则使用编译后的本地代码执行;如果不存在,则将方法的调用计数器加1,然后判断方法调用计数器和回边计数器之和是否超过方法调用计数器的阈值。如果超过,则会向JIT编译器提交一个该方法的代码编译请求。</p><p>上面的阈值可以使用<code>-XX:CompileThreshold</code>设定,默认值在Client模式下是1500,在Server模式下是10000。</p><p>方法调用计数器统计的并不是方法被调用的绝对次数,而是在一定时间范围内的次数。超过这个时间范围,这个方法计数器就会减少一半,这个过程称为热度衰减,这个时间周期称为半衰周期。可以通过<code>-XX:CounterHalfLifeTime</code>设置半衰周期(单位S),<code>-XX:-UseCounterDecay</code>来关闭热度衰减。</p><h3 id="模式设置"><a href="#模式设置" class="headerlink" title="模式设置"></a>模式设置</h3><p>默认情况下,hotspot采用混合模式架构(即解释器和JIT编译器并存的架构),我们可以通过下面这些指令来切换模式:</p><ul><li><code>-Xint</code>:完全采用解释器模式执行程序;</li><li><code>-Xcomp</code>:完全采用即时编译器模式执行程序,如果即时编译器出现问题,解释器会介入执行;</li><li><code>-Xmixed</code>:混合模式。</li></ul><p><img src="img/[email protected]" alt="QQ20200706-141640@2x"></p><h3 id="JIT编译器分类"><a href="#JIT编译器分类" class="headerlink" title="JIT编译器分类"></a>JIT编译器分类</h3><p>hotspot内置两种JIT编译器:Client Compiler和Server Compiler,也称为C1编译器和C2编译器。我们可以通过下面这些指令来指定使用哪种JIT编译器:</p><ul><li><p><code>-client</code>:指定Java虚拟机运行在Client模式下,并使用C1编译器。C1编译器会对字节码进行简单和可靠的优化,耗时短,已达到更快的编译速度;</p></li><li><p><code>-server</code>:指定Java虚拟机运行在Server模式下,并使用C2编译器。C2编译器进行耗时较长的优化,以及激进优化,虽然编译耗时更长,但代码执行效率更高(64位JDK只支持Server模式)。</p></li></ul><blockquote><p>参考文章:</p></blockquote><p><a href="https://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html" target="_blank" rel="noopener">https://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html</a></p><p><a href="https://docs.oracle.com/en/java/javase/11/tools/java.html" target="_blank" rel="noopener">https://docs.oracle.com/en/java/javase/11/tools/java.html</a></p><p><a href="https://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html" target="_blank" rel="noopener">https://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html</a></p><p><a href="http://www.atguigu.com/download_detail.shtml?v=279" target="_blank" rel="noopener">http://www.atguigu.com/download_detail.shtml?v=279</a></p><script>$(".post-body a").not(".thispage").addClass("ignore-href").attr("target","_blank")</script></div><div></div><div><div style="padding:10px 0;margin:20px auto;width:90%;text-align:center;color:#878787" id="reward-div"><div>请作者喝瓶肥宅水🥤</div><button id="rewardButton" style="margin-top:10px" disable="enable" onclick='var e=document.getElementById("QR");"none"===e.style.display?e.style.display="block":e.style.display="none"'><span style="height:46px;width:46px;line-height:46px;border-radius:50%;color:#fe5f55;font-weight:600;background:#ffd5be;border:none;box-shadow:0 4px 8px 0 rgba(255,213,190,.4)">¥</span></button><div id="QR" style="display:none"><div id="wechat" style="display:inline-block"><img id="wechat_qr" src="/img/wechat_pay.png" alt="MrBird WeChat Pay"></div><div id="alipay" style="display:inline-block"><img id="alipay_qr" src="/img/ali_pay.png" alt="MrBird Alipay"></div></div></div><style>#QR img{width:auto;margin:.8em 1em 0 1em}</style></div><div><ul class="post-copyright"><li class="post-copyright-author"><strong>本文作者:</strong> MrBird</li><li class="post-copyright-link"><strong>本文链接:</strong> <a href="http://mrbird.cc/JVM-Learn.html" title="JVM学习笔记">http://mrbird.cc/JVM-Learn.html</a></li><li class="post-copyright-license"><strong>版权声明: </strong>本博客所有文章除特别声明外,均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处!</li></ul></div><footer class="post-footer"><div class="post-tags" style="margin-bottom:1.3rem"><a href="/tags/Java/" rel="tag"># Java</a></div><div class="post-nav"><div class="post-nav-next post-nav-item"><a href="/Java-BlockingQueue.html" rel="next" title="Java BlockingQueue && BlockingDeque"><i class="fa fa-chevron-left"></i> Java BlockingQueue && BlockingDeque</a></div><span class="post-nav-divider"></span><div class="post-nav-prev post-nav-item"><a href="/Java方法调用细节.html" rel="prev" title="Java方法调用细节">Java方法调用细节 <i class="fa fa-chevron-right"></i></a></div></div></footer></article><hr><div id="container"></div><div class="post-spread"><div id="comment-div"></div><style>.valine .vlist{margin-bottom:3rem}.valine .vwrap .vcontrol .col.col-60{text-align:left}.valine .vlist .vcard .vhead,.valine .vlist .vcard section .vfooter{text-align:left}.valine .vlist .vcard section{padding-bottom:.5rem!important}.vname{color:#6db33f!important}div#comment-div{margin-bottom:-8rem}.valine .vlist .vcard .vcontent .code,.valine .vlist .vcard .vcontent code,.valine .vlist .vcard .vcontent pre{background:#fbfbfb}.valine .vlist .vcard .vcontent a{color:#6db33f}.valine .vlist .vcard .vimg{border-radius:3px}.valine .vinfo{text-align:left}.valine .vbtn{border-radius:2px;padding:.3rem 1.25rem}.valine .vbtn:active,.valine .vbtn:hover{color:#6db33f;border-color:#6db33f;background-color:#fff}.valine .vwrap .vheader .vinput:focus{border-bottom-color:#6db33f}.valine .vlist .vcard .vcontent.expand:before{background:-webkit-gradient(linear,left top,left bottom,from(hsla(0,0%,100%,0)),to(hsla(0,0%,100%,.2)));background:linear-gradient(180deg,hsla(0,0%,100%,0),hsla(0,0%,100%,.2))}.valine .vlist .vcard .vcontent.expand:after{content:"点击展开";font-size:.4rem;text-align:right;left:-1rem;background:hsla(0,0%,100%,.2)}.valine .vlist .vcard section .vfooter .vat{color:#b3b3b3}.valine .vlist .vcard section .vfooter .vat:hover{color:#6db33f}.vcontent img{margin:0}.valine .info{display:none}</style><script type="text/javascript" src="/js/av.min.js"></script><script type="text/javascript" src="/js/Valine.min.js"></script><script type="text/javascript" src="/js/activate-power-mode.js"></script><script>POWERMODE.colorful=!0,POWERMODE.shake=!1,document.body.addEventListener("input",POWERMODE),new Valine({el:"#comment-div",notify:!1,verify:!0,appId:"SMcDFP1bN1jgb9Lo8JmtICHm-gzGzoHsz",appKey:"dH4nrUrt3V5XiJiI6Qyejnbi",placeholder:"",path:window.location.pathname,avatar:"monsterid",guest_info:["nick","mail","link"]});var chicken='<a href="#"><img src="https://image.uisdc.com/wp-content/uploads/2018/06/uisdc-chat-chicken.gif" class="checken"></a>';$("#comment-div").prepend(chicken)</script></div></div><script>var $bqinline=$("img[alt='bq-inline']");$bqinline.css({width:"2.3rem",height:"2.3rem",display:"inline","vertical-align":"text-bottom"})</script></div><div class="comments" id="comments"></div></div><aside id="sidebar" class="sidebar" onselectstart="return!1"><div class="sidebar-inner"><ul class="sidebar-nav motion-element"><li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">Contents</li><li class="sidebar-nav-overview" data-target="site-overview">Site Preview</li></ul><section class="site-overview sidebar-panel"><div class="sidebar-sticky sticky"><div itemscope itemtype="https://mrbird.cc"><div class="author__header"><div class="author__avatar"><img src="/images/blogImage.jpg" class="author__avatar" alt="MrBird" itemprop="image"></div><div class="author__content"><div class="author__name" itemprop="name">MrBird</div><p class="author__bio" itemprop="description">A simple blog, code repository, just keep blogging</p></div><div class="author__count"><a href="/archives" class="ignore-href"><span class="count">14</span> <span>Archives</span> </a><a href="/tags" class="ignore-href"><span class="count">2</span> <span>Labels</span></a></div></div><div class="author__urls-wrapper"><ul class="author__urls social-icons"><li><a href="/" itemprop="url" class="ignore-href">🏠 Home</a></li><li><a href="/archives" itemprop="url" class="ignore-href">📦 Archives</a></li><li><a href="/tags" itemprop="url" class="ignore-href">🔖 Labels</a></li><li><a href="/friends" itemprop="url" class="ignore-href">👬 Friends</a></li><li><a href="javascript:;" class="popup-trigger animsition-link">🔍 Search</a></li></ul></div></div></div></section><section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active"><div class="post-toc"><div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#JVM结构"><span class="nav-number">1.</span> <span class="nav-text">JVM结构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#类加载器"><span class="nav-number">2.</span> <span class="nav-text">类加载器</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#类加载器分类"><span class="nav-number">2.1.</span> <span class="nav-text">类加载器分类</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#启动类加载器"><span class="nav-number">2.1.1.</span> <span class="nav-text">启动类加载器</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#拓展类加载器"><span class="nav-number">2.1.2.</span> <span class="nav-text">拓展类加载器</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#应用程序类加载器"><span class="nav-number">2.1.3.</span> <span class="nav-text">应用程序类加载器</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#用户自定义加载器"><span class="nav-number">2.1.4.</span> <span class="nav-text">用户自定义加载器</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#类加载步骤"><span class="nav-number">2.2.</span> <span class="nav-text">类加载步骤</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#加载Loading"><span class="nav-number">2.2.1.</span> <span class="nav-text">加载Loading</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#链接Linking"><span class="nav-number">2.2.2.</span> <span class="nav-text">链接Linking</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#初始化Initialization"><span class="nav-number">2.2.3.</span> <span class="nav-text">初始化Initialization</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#双亲委派机制"><span class="nav-number">2.3.</span> <span class="nav-text">双亲委派机制</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#程序计数器"><span class="nav-number">3.</span> <span class="nav-text">程序计数器</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#虚拟机栈(Java栈)"><span class="nav-number">4.</span> <span class="nav-text">虚拟机栈(Java栈)</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#虚拟机栈大小调整"><span class="nav-number">4.1.</span> <span class="nav-text">虚拟机栈大小调整</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#栈帧内部结构"><span class="nav-number">4.2.</span> <span class="nav-text">栈帧内部结构</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#局部变量表"><span class="nav-number">4.2.1.</span> <span class="nav-text">局部变量表</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#操作数栈"><span class="nav-number">4.2.2.</span> <span class="nav-text">操作数栈</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#动态链接"><span class="nav-number">4.2.3.</span> <span class="nav-text">动态链接</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#方法返回地址"><span class="nav-number">4.2.4.</span> <span class="nav-text">方法返回地址</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#一些附加信息"><span class="nav-number">4.2.5.</span> <span class="nav-text">一些附加信息</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#本地方法接口"><span class="nav-number">5.</span> <span class="nav-text">本地方法接口</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#本地方法栈"><span class="nav-number">6.</span> <span class="nav-text">本地方法栈</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#堆(Heap)"><span class="nav-number">7.</span> <span class="nav-text">堆(Heap)</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#堆空间对象分配过程"><span class="nav-number">7.1.</span> <span class="nav-text">堆空间对象分配过程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#堆参数"><span class="nav-number">7.2.</span> <span class="nav-text">堆参数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#TLAB"><span class="nav-number">7.3.</span> <span class="nav-text">TLAB</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#方法区"><span class="nav-number">8.</span> <span class="nav-text">方法区</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#设置方法区大小"><span class="nav-number">8.1.</span> <span class="nav-text">设置方法区大小</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#方法区、堆、栈关系"><span class="nav-number">8.2.</span> <span class="nav-text">方法区、堆、栈关系</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#方法区内部结构"><span class="nav-number">8.3.</span> <span class="nav-text">方法区内部结构</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#类型信息"><span class="nav-number">8.3.1.</span> <span class="nav-text">类型信息</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#方法信息"><span class="nav-number">8.3.2.</span> <span class="nav-text">方法信息</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#域信息"><span class="nav-number">8.3.3.</span> <span class="nav-text">域信息</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#JIT代码缓存"><span class="nav-number">8.3.4.</span> <span class="nav-text">JIT代码缓存</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#运行时常量池"><span class="nav-number">8.3.5.</span> <span class="nav-text">运行时常量池</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#静态变量"><span class="nav-number">8.3.6.</span> <span class="nav-text">静态变量</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#演示方法区内部结构"><span class="nav-number">8.3.7.</span> <span class="nav-text">演示方法区内部结构</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#方法区的演进"><span class="nav-number">8.4.</span> <span class="nav-text">方法区的演进</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#方法区垃圾回收"><span class="nav-number">8.5.</span> <span class="nav-text">方法区垃圾回收</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#执行引擎"><span class="nav-number">9.</span> <span class="nav-text">执行引擎</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#解释器和JIT编译器"><span class="nav-number">9.1.</span> <span class="nav-text">解释器和JIT编译器</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#热点代码"><span class="nav-number">9.1.1.</span> <span class="nav-text">热点代码</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#模式设置"><span class="nav-number">9.2.</span> <span class="nav-text">模式设置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#JIT编译器分类"><span class="nav-number">9.3.</span> <span class="nav-text">JIT编译器分类</span></a></li></ol></li></ol></div></div></section></div><div id="asider-footer"><div id="links"><li><a href="https://love.mrbird.cc" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-diamond" aria-hidden="true"></i></a></li><li><a href="https://cloud.mrbird.cn" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-skyatlas" aria-hidden="true"></i></a></li><li><a href="https://gitee.com/mrbirdd" target="_blank" itemprop="sameAs" class="ignore-href"><i class="fa fa-fw fa-codepen" aria-hidden="true"></i></a></li><li><a href="https://github.com/wuyouzhuguli" target="_blank" itemprop="sameAs" class="ignore-href"><i class="fa fa-fw fa-github-alt" aria-hidden="true"></i></a></li></div><div id="author"></div><script type="text/javascript">var $smsheoschzd100dn="@ 2016 - "+(new Date).getFullYear()+" MrBird";document.getElementById("author").innerHTML=$smsheoschzd100dn</script><div><script type="text/javascript" src="/js/busuanzi.js"></script> UV <span class="busuanzi-value" id="busuanzi_value_site_uv" style="cursor:pointer" title="统计开始时间:2019年7月5日"></span> PV <span class="busuanzi-value" id="busuanzi_value_site_pv" style="cursor:pointer" title="统计开始时间:2019年7月5日"></span></div></div><script>function c__(){var o=sidebar_nav_toc.attr("class");o.indexOf("active")!=-1?footer.hide(300):footer.show(300)}var sidebar_nav_toc=$(".sidebar-nav-toc"),footer=$("#asider-footer");c__(),$(".sidebar-nav").on("click",function(){c__()})</script></aside></div></main><div class="back-to-top"><span id="scrollpercent"><span>0</span></span></div></div><script type="text/javascript">"[object Function]"!==Object.prototype.toString.call(window.Promise)&&(window.Promise=null)</script><script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script><script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script><script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script><script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script><script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script><script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script><script type="text/javascript">function proceedsearch(){$("body").append('<div class="search-popup-overlay local-search-pop-overlay"></div>').css("overflow","hidden"),$(".search-popup-overlay").click(onPopupClose),$(".popup").toggle();var t=$("#local-search-input");t.attr("autocapitalize","none"),t.attr("autocorrect","off"),t.focus()}var isfetched=!1,isXml=!0,search_path="search.xml";0===search_path.length?search_path="search.xml":search_path.endsWith("json")&&(isXml=!1);var path="/"+search_path,onPopupClose=function(t){$(".popup").hide(),$("#local-search-input").val(""),$(".search-result-list").remove(),$("#no-result").remove(),$(".local-search-pop-overlay").remove(),$("body").css("overflow","")},searchFunc=function(t,e,o){"use strict";$("body").append('<div class="search-popup-overlay local-search-pop-overlay"><div id="search-loading-icon"><i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i></div></div>').css("overflow","hidden"),$("#search-loading-icon").css("margin","20% auto 0 auto").css("text-align","center"),$.ajax({url:t,dataType:isXml?"xml":"json",async:!0,success:function(t){isfetched=!0,$(".popup").detach().appendTo(".header-inner");var n=isXml?$("entry",t).map(function(){return{title:$("title",this).text(),content:$("content",this).text(),url:$("url",this).text()}}).get():t,r=document.getElementById(e),s=document.getElementById(o),a=function(){var t=r.value.trim().toLowerCase(),e=t.split(/[\s\-]+/);e.length>1&&e.push(t);var o=[];if(t.length>0&&n.forEach(function(n){function r(e,o,n,r){for(var s=r[r.length-1],a=s.position,i=s.word,l=[],h=0;a+i.length<=n&&0!=r.length;){i===t&&h++,l.push({position:a,length:i.length});var p=a+i.length;for(r.pop();0!=r.length&&(s=r[r.length-1],a=s.position,i=s.word,p>a);)r.pop()}return c+=h,{hits:l,start:o,end:n,searchTextCount:h}}function s(t,e){var o="",n=e.start;return e.hits.forEach(function(e){o+=t.substring(n,e.position);var r=e.position+e.length;o+='<b class="search-keyword">'+t.substring(e.position,r)+"</b>",n=r}),o+=t.substring(n,e.end)}var a=!1,i=0,c=0,l=n.title.trim(),h=l.toLowerCase(),p=n.content.trim().replace(/<[^>]+>/g,""),u=p.toLowerCase(),f=decodeURIComponent(n.url),d=[],g=[];if(""!=l&&(e.forEach(function(t){function e(t,e,o){var n=t.length;if(0===n)return[];var r=0,s=[],a=[];for(o||(e=e.toLowerCase(),t=t.toLowerCase());(s=e.indexOf(t,r))>-1;)a.push({position:s,word:t}),r=s+n;return a}d=d.concat(e(t,h,!1)),g=g.concat(e(t,u,!1))}),(d.length>0||g.length>0)&&(a=!0,i=d.length+g.length)),a){[d,g].forEach(function(t){t.sort(function(t,e){return e.position!==t.position?e.position-t.position:t.word.length-e.word.length})});var v=[];0!=d.length&&v.push(r(l,0,l.length,d));for(var C=[];0!=g.length;){var $=g[g.length-1],m=$.position,x=$.word,w=m-20,y=m+80;w<0&&(w=0),y<m+x.length&&(y=m+x.length),y>p.length&&(y=p.length),C.push(r(p,w,y,g))}C.sort(function(t,e){return t.searchTextCount!==e.searchTextCount?e.searchTextCount-t.searchTextCount:t.hits.length!==e.hits.length?e.hits.length-t.hits.length:t.start-e.start});var T=parseInt("1");T>=0&&(C=C.slice(0,T));var b="";b+=0!=v.length?"<li><a href='"+f+"' class='search-result-title'>"+s(l,v[0])+"</a>":"<li><a href='"+f+"' class='search-result-title'>"+l+"</a>",C.forEach(function(t){b+="<a href='"+f+'\'><p class="search-result">'+s(p,t)+"...</p></a>"}),b+="</li>",o.push({item:b,searchTextCount:c,hitCount:i,id:o.length})}}),1===e.length&&""===e[0])s.innerHTML='<div id="no-result"><i class="fa fa-search fa-5x" /></div>';else if(0===o.length)s.innerHTML='<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>';else{o.sort(function(t,e){return t.searchTextCount!==e.searchTextCount?e.searchTextCount-t.searchTextCount:t.hitCount!==e.hitCount?e.hitCount-t.hitCount:e.id-t.id});var a='<ul class="search-result-list">';o.forEach(function(t){a+=t.item}),a+="</ul>",s.innerHTML=a}};r.addEventListener("input",a),$(".local-search-pop-overlay").remove(),$("body").css("overflow",""),proceedsearch()}})};$(".popup-trigger").click(function(t){t.stopPropagation(),isfetched===!1?searchFunc(path,"local-search-input","local-search-result"):proceedsearch()}),$(".popup-btn-close").click(onPopupClose),$(".popup").click(function(t){t.stopPropagation()}),$(document).on("keyup",function(t){var e=27===t.which&&$(".search-popup").is(":visible");e&&onPopupClose()})</script></body><script>$(function(){$("a").not(".nav-link,.cloud-tie-join-count,.ignore-href,.jstree-anchor").addClass("animsition-link")});var burst1=new mojs.Burst({left:0,top:0,radius:{5:40},children:{shape:"circle",fill:["red","cyan","orange"],fillOpacity:.8,radiusX:3.5,radiusY:3.5}});document.addEventListener("click",function(a){null==a.target.href&&"footer"!=a.target.className&&"copyright"!=a.target.className&&"author__urls social-icons"!=a.target.className&&"author__avatar"!=a.target.className&&"sidebar sidebar-active"!=a.target.className&&burst1.tune({x:a.pageX,y:a.pageY}).generate().replay()})</script><script type="text/javascript" src="/js/message.js"></script></html><!-- rebuild by neat -->