0% found this document useful (0 votes)
161 views471 pages

深入理解Java虚拟机(第二版 带目录)

This document provides an overview of the Java programming language and Java Virtual Machine (JVM). It discusses the history and components of Java, including the JVM, Java Development Kit (JDK), garbage collection, and Java profiling tools. It also covers topics like Java classes, threads, JIT compilation, and Java applications and frameworks. The document contains several chapters and sections focusing on these various technical aspects of the Java platform.

Uploaded by

Da Ming
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
161 views471 pages

深入理解Java虚拟机(第二版 带目录)

This document provides an overview of the Java programming language and Java Virtual Machine (JVM). It discusses the history and components of Java, including the JVM, Java Development Kit (JDK), garbage collection, and Java profiling tools. It also covers topics like Java classes, threads, JIT compilation, and Java applications and frameworks. The document contains several chapters and sections focusing on these various technical aspects of the Java platform.

Uploaded by

Da Ming
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 471

Java

——JVM

ISBN 978-7-111-42190-0

2013

+ 86-10-68995265

[email protected]

www.hzmedia.com.cn

@yanfabook
2 1

Java
1 Java
1.1
1.2 Java
1.3 Java
1.4 Java
1.4.1 Sun Classic/Exact VM
1.4.2 Sun HotSpot VM
1.4.3 Sun Mobile-Embedded VM/Meta-Circular VM
1.4.4 BEA JRockit/IBM J9 VM
1.4.5 Azul VM/BEA Liquid VM
1.4.6 Apache Harmony/Google Android Dalvik VM
1.4.7 Microsoft JVM
1.5 Java
1.5.1
1.5.2
1.5.3
1.5.4
1.5.5 64
1.6 JDK
1.6.1 JDK
1.6.2
1.6.3
1.6.4
1.6.5 IDE
1.7

2 Java
2.1
2.2
2.2.1
2.2.2 Java
2.2.3
2.2.4 Java
2.2.5
2.2.6
2.2.7
2.3 HotSpot
2.3.1
2.3.2
2.3.3
2.4 OutOfMemoryError
2.4.1 Java
2.4.2
2.4.3
2.4.4
2.5
3
3.1
3.2
3.2.1
3.2.2
3.2.3
3.2.4
3.2.5
3.3
3.3.1 -
3.3.2
3.3.3 -
3.3.4
3.4 HotSpot
3.4.1
3.4.2
3.4.3
3.5
3.5.1 Serial
3.5.2 ParNew
3.5.3 Parallel Scavenge
3.5.4 Serial Old
3.5.5 Parallel Old
3.5.6 CMS
3.5.7 G1
3.5.8 GC
3.5.9
3.6
3.6.1 Eden
3.6.2
3.6.3
3.6.4
3.6.5
3.7
4
4.1
4.2 JDK
4.2.1 jps
4.2.2 jstat
4.2.3 jinfo Java
4.2.4 jmap Java
4.2.5 jhat
4.2.6 jstack Java
4.2.7 HSDIS JIT
4.3 JDK
4.3.1 JConsole Java
4.3.2 VisualVM
4.4
5
5.1
5.2
5.2.1
5.2.2
5.2.3
5.2.4
5.2.5 JVM
5.2.6
5.2.7 Windows
5.3 Eclipse
5.3.1
5.3.2 JDK 1.6
5.3.3
5.3.4
5.3.5
5.4

6
6.1
6.2
6.3 Class
6.3.1 Class
6.3.2
6.3.3
6.3.4
6.3.5
6.3.6
6.3.7
6.4
6.4.1
6.4.2
6.4.3
6.4.4
6.4.5
6.4.6
6.4.7
6.4.8
6.4.9
6.4.10
6.5
6.6 Class
6.7
7
7.1
7.2
7.3
7.3.1
7.3.2
7.3.3
7.3.4
7.3.5
7.4
7.4.1
7.4.2
7.4.3
7.5
8
8.1
8.2
8.2.1
8.2.2
8.2.3
8.2.4
8.2.5
8.3
8.3.1
8.3.2
8.3.3
8.4
8.4.1
8.4.2
8.4.3
8.5
9
9.1
9.2
9.2.1 Tomcat
9.2.2 OSGi
9.2.3
9.2.4 Retrotranslator JDK
9.3
9.3.1
9.3.2
9.3.3
9.3.4
9.4

10
10.1
10.2 Javac
10.2.1 Javac
10.2.2
10.2.3
10.2.4
10.3 Java
10.3.1
10.3.2
10.3.3
10.4
10.4.1
10.4.2
10.4.3
10.4.4
10.5
11
11.1
11.2 HotSpot
11.2.1
11.2.2
11.2.3
11.2.4
11.3
11.3.1
11.3.2
11.3.3
11.3.4
11.3.5
11.4 Java C/C++
11.5

12 Java
12.1
12.2
12.3 Java
12.3.1
12.3.2
12.3.3 volatile
12.3.4 long double
12.3.5
12.3.6
12.4 Java
12.4.1
12.4.2 Java
12.4.3
12.5
13
13.1
13.2
13.2.1 Java
13.2.2
13.3
13.3.1
13.3.2
13.3.3
13.3.4
13.3.5
13.4

A Windows OpenJDK
A.1 JDK
A.2
A.3
A.4
A.5
B
C HotSpot
C.1
C.2
C.3
C.4
C.5
C.6
D OQL
D.1 SELECT
D.2 FROM
D.3 WHERE
D.4
D.5 OQL BNF
E JDK
Java Java
Java Java API Java
Java Spring Struts Java API Java
Java

Java

Java
Java
C/C++
Java API Java

Java

10 10000
10000

Java

Java

Java
Java
Java
2 1
JDK 1.7 2011 7 28 2006 JDK 1.6 JDK
2 JDK 1.6
JDK 1.7 JDK 1.7 G1 JDK 1.7 JSR-292
InvokeDynamic Java

1 OpenJDK
1 OpenJDK “ ”
2 1
OpenJDK OpenJDK
HotSpot JIT

Java
2
JVM GC JIT
1 2 JVM

2 1
1 http://icyfenix.iteye.com/blog/1119214
1 Java

Java

3
Java

Java

Java API Java

http://www.hzbook.com

HotSpot JRockit WebLogic Sun


BEA BEA Sun 2008 2009 Oracle
Java

JDK 1.5 “JDK 1.5”


Developer Version java-version
1.5 1.6 1.7 Product Version JDK 5 JDK 6 JDK
7

Sun JDK 1.7


Java

Java
OpenJDK Java
Java Java 1

1 Java
OpenJDK 7

Java

2
5

3 JDK 1.7
Java

4 JDK 6

5
“ ”

6 9

6 Class
Class

7 “ ” “ ” “ ” “ ” “ ”5

9 4
Java
10 11

10 Java

11 HotSpot
JIT

Java

12 13

12 Java
Java Java

13
“ Java ”
Java

The Java Virtual Machine Specification,Java SE 7 Edition [1]

“Java ” Sun
Sun Classic VM

Java SE 7 2011 7 1999


Java 2 Java SE 7
PDF [2]

The Java Language Specification,Java SE 7 Edition [3]

Java Java
Java Sun
Java James Gosling Java
PDF Java 3
2005 7

Oracle JRockit The Definitive Guide

Oracle JRockit 2010 7


JRockit JRockit Mission Control
TeamLeader JRockit JRockit HotSpot

Inside the Java 2 Virtual Machine,Second Edition

Java 2 2000 1 2003


Java

Java Performance

Java Performance “The Java” Effective


Java 2011 10
Java 3 4 7 Java Java
Java

2
http://hllvm.group.iteye.com/

JVM
High-Level Language Virtual Machine ITEye
Java RednaxelaFX http://rednaxelafx.iteye.com/

HotSpot Internals https://wikis.oracle.com/display/HotSpotInternals/Home

OpenJDK Wiki JDK

The HotSpot Group http://openjdk.java.net/groups/hotspot/

HotSpot 4
HotSpot

[1] http://docs.oracle.com/javase/specs/jvms/se7/jvms7.pdf
[2] http://docs.oracle.com/javase/specs/jls/se7/jls7.pdf
[3] http://icyfenix.iteye.com/blog/1256329

[email protected]

2 http://icyfenix.iteye.com/
Oracle
Java
1 Java
1 Java

1.1
Java

1-1 Java
900 Java
11 30
[1]

1-1 Java

Java
“ ”

Java

……Java
Java Java
Java
“ ”
“ ”

Java
Java Java

[1] Java http://www.java.com/zh_CN/about/


1.2 Java
Clojure JRuby Groovy Java
Java Sun Java

Java

Java

Class

Java API

Java

Java Java Java API JDK Java


Development Kit JDK Java
JDK Java Java API Java
SE API [1]
Java JRE Java Runtime Environment JRE Java
1-2 Java JDK JRE
1-2 Java [2]

Java Java 4

Java Card Java Applets

Java ME Micro Edition Java PDA


Java API J2ME

Java SE Standard Edition Windows Java


Java API J2SE

Java EE Enterprise Edition ERP CRM


Java Java SE API [3]

J2EE

[1]JDK 1.7 Java SE API http://download.oracle.com/javase/7/docs/api/


[2] http://download.oracle.com/javase/7/docs/
[3] javax.* java.* Java SE API
API
javax.*
1.3 Java
Java 18 18
1-3 JDK 1.7 18
Java Java
Java

1-3 Java

1991 4 James Gosling Green Project

Java Oak Oak


1995 Oak
Java

1995 5 23 Oak Java SunWorld Java 1.0


Java “Write Once,Run Anywhere”

1996 1 23 JDK 1.0 Java JDK 1.0


Java Sun Classic VM JDK 1.0
Java Applet AWT

1996 4 10 Java 9
8.3 Java 1996 5 Sun
JavaOne JavaOne Java

1997 2 19 Sun JDK 1.1 Java JDBC


JDK 1.1 JDK 1.1 JAR JDBC
JavaBeans RMI Java Inner Class
Reflection
1999 4 8 JDK 1.1 1.1.0 1.1.8 1.1.4 JDK
JDK 1.1.4-Sparkler JDK 1.1.5-
Pumpkin JDK 1.1.6-Abigail JDK 1.1.7-Brutus
JDK 1.1.8-Chelsea

1998 12 4 JDK JDK 1.2 Playground


Sun Java 3
J2SE Java 2 Platform,Standard Edition J2EE Java 2 Platform,Enterprise
Edition J2ME Java 2 Platform,Micro Edition
EJB Java Plug-in Java IDL Swing
Java JIT Just In Time JDK 1.2 3 Classic
VM HotSpot VM Exact VM Exact VM Solaris
JIT Classic VM JIT
API Java strictfp Java Collections
1999 3 7 JDK 1.2.1 JDK 1.2.2

1999 4 27 HotSpot HotSpot “Longview


Technologies” HotSpot 1997 Sun
HotSpot JDK 1.2 JDK 1.3
Sun JDK

2000 5 8 Kestrel JDK 1.3 JDK 1.3 JDK 1.2


Timer API JNDI JDK 1.3
JNDI CORBA IIOP RMI
Java 2D Java 2D API
JavaSound JDK 1.3 1 JDK 1.3.1 Ladybird
2001 5 17

JDK 1.3 Sun JDK

2002 2 13 JDK 1.4 Merlin JDK 1.4 Java


Compaq Fujitsu SAS Symbian IBM
JDK 1.4 Spring Hibernate Struts
JDK 1.4 JDK 1.4 JDK 1.4
NIO XML XSLT
JDK 1.4 2002 9 16 Grasshopper
JDK 1.4.1 2003 6 26 Mantis JDK 1.4.2

2002 Java Java


.NET Framework
Java Java .NET Java

2004 9 30 JDK 1.5 [1]


Tiger JDK 1.2 Java
JDK 1.5 Java
foreach JDK
1.5 API Java Java Memory
Model,JMM java.util.concurrent JDK 1.5
Windows 9x JDK

2006 12 11 JDK 1.6 Mustang Sun


JDK 1.2 8 J2EE J2SE J2ME Java SE 6 Java EE
6 Java ME 6 JDK 1.6 Mozilla
JavaScript Rhino API HTTP API Java

2006 11
13 JavaOne Sun Java
JDK GPL v2 GNU General Public License v2
OpenJDK
Encumbered Code Sun OpenJDK
Sun JDK OpenJDK JDK 1.7 Sun JDK
OpenJDK OpenJDK 7 Sun JDK
1.7

JDK 1.6 JDK JavaFX Sun


Sun JDK JDK
JDK 1.6 37 Update Java
SE 6 Update 37 2012 10 16

2009 2 19 Dolphin JDK 1.7


JDK 1.7 10 2010 9 9
JDK 1.7

JDK 1.7 JDK


Lambda Lambda Jigsaw
GarbageFirst Coin Java
JDK 1.7 Sun
3% JDK 1.7
JDK 1.7 “ ” Oracle Sun “B ”
JDK 1.7 JDK 1.7 2011 7 28 “B
” Lambda Jigsaw Coin JDK 1.8
JDK 1.7 G1 G1 Experimental
2012 4 Update 4 “ ” Java JSR-
292

JDK 1.7 9 Update Java SE 7 Update 9 2012 10


16 Java SE 7 Update 4 Oracle Mac OS X Update 6
Update 6 ARM
JDK Windows Windows 9x Linux Solaris Mac OS
ARM x86 x64 Sparc
2009 4 20 Oracle 74 Sun Java
Oracle Java JCP JCP
Sun Oracle Oracle
BEA Sun Oracle BEA Sun
JRockit HotSpot,Oracle 1 2
[2]

Java

Oracle JDK 1.8 2013 9 JDK 1.8


JDK 1.7 JDK 1.7 Lambda
Jigsaw Oracle Jigsaw JDK 1.8 JDK
1.9 JDK 1.7 Coin

2011 JavaOne Oracle JDK 1.9 Java


GB Java Java

[1]JDK 1.5 JDK 1.5


Developer Version java-version
1.5 1.6 1.7 Product Version JDK 5 JDK 6 JDK 7

[2]“HotRockit” http://hirt.se/presentations/WhatToExpect.ppt
1.4 Java
Java Java Java
Sun HotSpot BEA JRockit
IBM J9 JVM

1996 Sun JDK 1.0 Sun Classic VM

Java

1.4.1 Sun Classic/Exact VM


Sun Classic VM
“ Java ”

1996 1 23 Sun JDK 1.0 Java


JDK Classic VM Java
JIT JIT JIT
java-version

java version"1.2.2"
Classic VM build JDK-1.2.2-001 green threads,sunwjit

“sunwjit” Sun Symantec JIT


shuJIT

JIT C/C++
“Java ”

Sun Classic VM JDK 1.2


Solaris Exact VM
Exact VM
Exact Memory Management Non-Conservative/Accurate Memory
Management
32 123456 reference 123456
123456 GC
Exact VM
Classic VM handler GC
123456 654321 reference
123456 654321
reference

Exact VM Classic VM
HotSpot VM Windows Linux
Classic VM JDK 1.2 Sun JDK
JDK 1.2 HotSpot VM Classic VM java-
hotspot HotSpot VM JDK 1.3 HotSpot VM Classic
VM “ ” java-classic JDK 1.4
Classic VM Exact VM Sun Labs Research
VM
1.4.2 Sun HotSpot VM
HotSpot VM Java Sun JDK OpenJDK
Java
“ ” Sun “Longview
Technologies” Java
Strongtalk VM Self “ C
50% ” Sun JIT
1997 Longview Technologies HotSpot
VM

HotSpot VM Sun
HotSpot
VM HotSpot HotSpot
GC Exact VM HotSpot Exact VM HotSpot VM
Sun VM Sun HotSpot Exact
HotSpot VM
JIT
OSR

2006 JavaOne Sun Java


JDK HotSpot VM GPL
OpenJDK HotSpot VM Sun JDK OpenJDK JDK

2008 2009 Oracle BEA Sun Oracle


Java JRockit VM HotSpot VM Oracle
JDK 8
HotSpot JRockit JRockit
MissionControl HotSpot JIT
1.4.3 Sun Mobile-Embedded VM/Meta-Circular VM
Sun
Sun

Java
Sun Java

1 KVM

KVM K “Kilobyte”
Android iOS

2 CDC/CLDC HotSpot Implementation

CDC/CLDC Connected Limited Device Configuration JSR-139/JSR-218


PDA Java CDC-HI VM
CLDC-HI VM CDC/CLDC Java ME
Android iOS Sun

3 Squawk VM

Squawk VM Sun Sun SPOT Sun Small Programmable Object


Technology WiFi Java Card Java

Java C I/O

4 JavaInJava

JavaInJava Sun 1997 1998


Java Java “ ” Meta-
Circular
JIT 20 Java

5 Maxine VM

Maxine VM JavaInJava Java


JVM C Java 2005
JavaInJava,Maxine VM “ ” JIT

HotSpot Client VM
1.4.4 BEA JRockit/IBM J9 VM
Sun Sun
BEA IBM

JRockit VM “ Java ” J9 VM
BEA 2002 Appeal Virtual Machines BEA

JRockit
JRockit MissionControl
Java

IBM J9 VM IBM Java Java


IBM J9 VM “IBM Technology for Java Virtual Machine”
IT4J J9 J9 VM IBM Ottawa
SmallTalk bug 8k
K8
Java J9 BEA JRockit IBM
J9 Sun HotSpot
J9 IBM Java
IBM IBM WebSphere IBM AIX z/OS Java
1.4.5 Azul VM/BEA Liquid VM
“ Java ” HotSpot JRockit J9
Azul VM BEA Liquid VM
“ ”

Azul VM Azul Systems HotSpot Azul Systems


Vega Java Azul VM CPU GB
GC
2010 Azul Systems
Zing JVM x86 Vega

Liquid VM JRockit VE Virtual Edition BEA


Hypervisor JRockit VM Liquid VM

/ Java
1.4.6 Apache Harmony/Google Android Dalvik VM
Harmony VM Dalvik VM “ ” “Java ”
Java
Java

Apache Harmony Apache Apache License


JDK 1.5 JDK 1.6 Java Java
Eclipse Tomcat Maven Java TCK
“Apache JDK”
“ Java ”
TCK Technology Compatibility Kit Apache Sun TCK
Oracle Sun
Apache JCP Java Community Process Java
“ ”

Sun JDK OpenJDK Apache Harmony


Harmony IBM Harmony
OpenJDK Harmony
Java IBM JDK 7 Google Android SDK
Android

Android
Java ME Android Java
Sun

Dalvik VM Android Dalvik


Dalvik VM Java Java Java
Class JVM Java
dex Dalvik Executable Class Java
Java API Dalvik VM Android
Android 2.2
1.4.7 Microsoft JVM
Java Java
“ ”
JVM

Java Java
Sun Java Java Windows
Java 1996 1998 JDK 1.2
Java Applets IE3
Java Applets Java Windows
Windows Java 1997 1998 PC
Magazine “ ” 1997 10 Sun

2000 Sun
Sun 10 Java
Java Windows XP SP3 Java
Sun Windows XP
[1]

Jim Cullinan “ 3 Sun


Windows Java ”

Sun Java
Java .NET
Java

JamVM.

cacaovm.

SableVM.

Kaffe.

Jelatine JVM.

NanoVM.

MRP.

Moxie JVM.

Jikes RVM.

[1]Sun
Sun “ Windows XP Java ”
1.5 Java
2005 Java 10 SunOne Java James Gosling
“Java ” James Gosling
Java
1 2 JDK

1.5.1

OSGi JCP [1]

Java 2007 Sun


JSR-277 Java Java Module System Java
IBM JSR-291 Java SE Dynamic Component
Support for Java SE OSGi R4.1 Sun
Java SE 6 JDK
Java SE 7 Sun JSR-294 Java
Improved Modularity Support in the Java Programming Language
JSR Sun JCP OpenJDK
Jigsaw Java Java
OSGi R5.0 Jigsaw Java 7 Java 8 2012
7 Java 9 Sun
Java

[1] Java OSGi


Equinox 1
1.5.2
Java Java
Java
Clojure
JRuby/Rails Java

API [1]

Clojure JRuby Groovy


Java JVM 1-4

1-4 JVM [2]


Java
“ ”
1-1
JVM

Java Java
JSR-292 Da Vinci Machine Nashorn
InvokeDynamic java.lang.invoke Java “Java ” “

[1] Java Java


dynalang http://dynalang.sourceforge.net/

[2] http://www.Slideshare.net/josebetomex/oow-2009-towards-a-universal-vm
1.5.3
CPU
JDK 1.5 java.util.concurrent
JDK 1.7 java.util.concurrent.forkjoin
Fork/Join 1-5
CPU
Fork/Join

1-5 Fork/Join [1]

Java 8 Lambda Java


Java
Java

OpenJDK Sumatra [2]

CPU
C CUDA Sumatra Java GPU Graphics
Processing Units APU Accelerated Processing Units
Java API Lambda JVM

JDK Apache Hadoop


Map/Reduce
TB Scala
Clojure Erlang

[1] http://www.ibm.com/developerworks/cn/java/j-lo-forkjoin/
[2]Sumatra http://openjdk.java.net/projects/sumatra/
1.5.4
Java 5 Java
Java
Java 7 Java 8 Java
Sun Oracle Java OpenJDK Coin [1]

Java switch “ ”
try-catch-finally
Coin

Coin JSR-335 Lambda Expressions for the Java TM Programming


Language Lambda [2]
Java

[1]Coin http://wikis.sun.com/display/ProjectCoin/Home
[2]Lambda http://openjdk.java.net/projects/lambda/
1.5.5 64
CPU 64 Java
64 Java 64
64 Java
32 10% 30%
64 32
15%

Java EE 4GB 64
32
Sun JDK 1.6 Update 14
-XX +UseCompressedOops
Ergonomics
Java
Java

64
32 64
64
1.6 JDK
JDK JDK
JDK Java
JDK Native
JDK Hack JDK

JDK Apache Harmony OpenJDK


Sun JDK JDK OpenJDK

1.6.1 JDK
OpenJDK Sun/OracleJDK OpenJDK 6 OpenJDK 7 OpenJDK
7u OpenJDK 8 JDK

Java OpenJDK Sun 2006 Java


“ ” IcedTea [1]

UltraViolet
[2]
OpenJDK “ ”
Sun JDK 1.5 Java Research License JRL
Java JRL JDK 1.6 Update 23
JRL Sun/OracleJDK OpenJDK
Oracle
JDK OpenJDK FreeType “ ”
Oracle JDK Open JDK
JRockit Java Flight Recorder JRockit MissionControl HotSpot
Oracle JDK

Oracle Joe Darcy OSCON 2011 [3]


OpenJDK
7 Oracle JDK 7 1-6
OpenJDK
Oracle JDK
1-6 OpenJDK Oracle JDK

OpenJDK 6 OpenJDK 7 OpenJDK 7u OpenJDK 8


1-7 Joe Darcy OSCON 2011 OpenJDK 7
JDK 6 JDK 6 JDK 6 Update 1 JDK 7 OpenJDK 7
JDK 7 OpenJDK 7
OpenJDK 7 Build 20 OpenJDK 6 JDK 7
TCK 6

1-7 OpenJDK 6 OpenJDK 7 OpenJDK 7u OpenJDK 8


2012 7 JDK 7 OpenJDK OpenJDK 7 Update JDK 7
OpenJDK 8 JDK
Bug

OpenJDK 6 OpenJDK 7 OpenJDK 7u OpenJDK 8


OpenJDK 7u 7u6

OpenJDK Mercurial Repository


Repository http://hg.openjdk.java.net/jdk7u/jdk7u

hg clone http://hg.openjdk.java.net/jdk7u/jdk7u-dev
cd jdk7u-dev
chmod 755 get_source.sh
./get_source.sh

Release Note
300 MB
Mercurial Git SVN ClearCase CVS

Source Bundle Releases http://jdk7.java.net/source.html

Mercurial OpenJDK 7
Update 6 Build b21 2012 8 28 99MB 339MB

[1]IcedTea http://icedtea.classpath.org/wiki/Main_Page
[2]UltraViolet https://www.reservoir.com/ q=uvform/form
[3] https://blogs.oracle.com/darcy/resource/OSCON/oscon2011_OpenJDKState.pdf
1.6.2
Linux MacOS Solaris OpenJDK Windows
Ubuntu 10.10 MacOS X 10.8.2
Windows A
Windows OpenJDK 6 Plug

README-builds.html
OpenJDK
“Building the source code for the JDK requires
a high level of technical expertise.Sun provides the source code primarily for technical experts who
want to conduct research. JDK Sun JDK

64 64 OpenJDK 32
32 OpenJDK 512MB
600MB 512MB 600MB
OpenJDK 600MB
3GB Product Debug
FastDebug 5GB
1.6.3
MacOS [1]
Linux
OpenJDK Windows Mac
OS XCode Command Line Tools for XCode Apple Developer
https://developer.apple.com/ SDK OpenJDK
Makefile 6u14 JDK OpenJDK
Hotspot JDK API JAXWS JAXP…… C++
Java Java JDK
JDK “Bootstrap JDK” OpenJDK 7 Bootstrap JDK JDK6 Update 14
JDK7 Update 4 1.7.1 Apache Ant
Java Ant

Linux Mac OS Bootstrap JDK Ant


Mac OS GCC XCode SDK Ubuntu GCC
4.3 GCC binutils Ubuntu 10.10 OpenJDK 7u4

sudo apt-get install build-essential gawk m4 openjdk-6-jdk


libasound2-dev libcups2-dev libxrender-dev xorg-dev xutils-dev
x11proto-print-dev binutils libmotif3 libmotif-dev ant

[1] OpenJDK 7u4 Mac OS JDK


Mac OS
1.6.4

OpenJDK
LANG ALT_BOOTDIR

export LANG=C

HashTable
ALT_BOOTDIR Bootstrap JDK Mac OS

export ALT_BOOTDIR=/Library/Java/JavaVirtualMachines/jdk1.7.0_04.jdk/Contents/Home

JAVA_HOME CLASSPATH
Makefile

unset JAVA_HOME
unset CLASSPATH

1-1 Shell

1-1

# HashTable NPE
export LANG=C
#Bootstrap JDK
export ALT_BOOTDIR=/Library/Java/JavaVirtualMachines/jdk1.7.0_04.jdk/Contents/Home
#
export ALLOW_DOWNLOADS=true
# CPU
export HOTSPOT_BUILD_JOBS=6
export ALT_PARALLEL_COMPILE_JOBS=6
# build
# false sanity JDK
# dev DEV_ONLY=true
export SKIP_COMPARE_IMAGES=true
#
export USE_PRECOMPILED_HEADER=true
#
export BUILD_LANGTOOLS=true
#export BUILD_JAXP=false
#export BUILD_JAXWS=false
#export BUILD_CORBA=false
export BUILD_HOTSPOT=true
export BUILD_JDK=true
#
#export SKIP_DEBUG_BUILD=false
#export SKIP_FASTDEBUG_BUILD=true
#export DEBUG_NAME=debug
# false javaws Java build
BUILD_DEPLOY=false
# false build
# build JDK build
BUILD_INSTALL=false
#
export ALT_OUTPUTDIR=/Users/IcyFenix/Develop/JVM/jdkBuild/openjdk_7u4/build
# "
# " Makefile 2
unset JAVA_HOME
unset CLASSPATH
make 2 1|tee $ALT_OUTPUTDIR/build.log

make sanity
1-2

1-2 make sanity


/Develop/JVM/jdkBuild/openjdk_7u4$make sanity
Build Machine Information
build machine=IcyFenix-RMBP.local
Build Directory Structure
CWD=/Users/IcyFenix/Develop/JVM/jdkBuild/openjdk_7u4
TOPDIR=.
LANGTOOLS_TOPDIR=./langtools
JAXP_TOPDIR=./jaxp
JAXWS_TOPDIR=./jaxws
CORBA_TOPDIR=./corba
HOTSPOT_TOPDIR=./hotspot
JDK_TOPDIR=./jdk
Build Directives
BUILD_LANGTOOLS=true
BUILD_JAXP=true
BUILD_JAXWS=true
BUILD_CORBA=true
BUILD_HOTSPOT=true
BUILD_JDK=true
DEBUG_CLASSFILES=
DEBUG_BINARIES=
…… ……
OpenJDK-specific settings
FREETYPE_HEADERS_PATH=/usr/X11R6/include
ALT_FREETYPE_HEADERS_PATH=
FREETYPE_LIB_PATH=/usr/X11R6/lib
ALT_FREETYPE_LIB_PATH=
Previous JDK Settings
PREVIOUS_RELEASE_PATH=USING-PREVIOUS_RELEASE_IMAGE
ALT_PREVIOUS_RELEASE_PATH=
PREVIOUS_JDK_VERSION=1.6.0
ALT_PREVIOUS_JDK_VERSION=
PREVIOUS_JDK_FILE=
ALT_PREVIOUS_JDK_FILE=
PREVIOUS_JRE_FILE=
ALT_PREVIOUS_JRE_FILE=
PREVIOUS_RELEASE_IMAGE=/Library/Java/JavaVirtualMachines/jdk1.7.0_04.jdk/Contents/Home
ALT_PREVIOUS_RELEASE_IMAGE=

Sanity check passed.

Makefile Sanity “Sanity check


passed.” “make” OpenJDK make
make all Core i7 3720QM/16GB RAM MacBook 6
OpenJDK 20

#--Build times----------
Target all_product_build
Start 2012-12-13 17 12 19
End 2012-12-13 17 31 07
00 01 19 corba
00 01 15 hotspot
00 00 14 jaxp
00 7 21 jaxws
00 8 11 jdk
00 00 28 langtools
00 18 48 TOTAL
-------------------------

OpenJDK build/j2sdk-image build-debug build-


fastdebug JDK JAVA_HOME
JDK -version

./java-version
openjdk version"1.7.0-internal-fastdebug"
O p e n J D K R u n t i m e E n v i r o n m e n t b u i l d 1.7.0-i n t e r n a l-f a s t d e b u g-icyfenix_2012_12_24_15_57-b00
OpenJDK 64-Bit Server VM build 23.0-b21-fastdebug,mixed mode

JDK HotSpot
HotSpot OpenJDK Makefile
hotspot/make Makefile
build/hotspot/outputdir/bsd_amd64_compiler2
[1]

0 drwxr-xr-x 15 IcyFenix staff 510B 12 13 17 24 debug


0 drwxr-xr-x 15 IcyFenix staff 510B 12 13 17 24 fastdebug
0 drwxr-xr-x 15 IcyFenix staff 510B 12 13 17 25 generated
0 drwxr-xr-x 15 IcyFenix staff 510B 12 13 17 24 jvmg
0 drwxr-xr-x 15 IcyFenix staff 510B 12 13 17 24 optimized
0 drwxr-xr-x 584 IcyFenix staff 19K 12 13 17 25 product
0 drwxr-xr-x 15 IcyFenix staff 510B 12 13 17 24 profiled

make

env.sh
“JAVA_HOME
CLASSPATH HOTSPOT_BUILD_USER”3
“LD_LIBRARY_PATH”

LD_LIBRARY_PATH=. ${JAVA_HOME}/jre/lib/amd64/native_threads ${JAVA_HOME}/jre/lib/amd64


export LD_LIBRARY_PATH

gamma

../env.sh
./gamma-version
Using java runtime at /Library/Java/JavaVirtualMachines/jdk1.7.0_04.jdk/Contents/Home/jre
java version"1.7.0_04"
Java TM SE Runtime Environment build 1.7.0_04-b21
OpenJDK 64-Bit Server VM build 23.0-b21 mixed mode

[1] bsd Mac OS


FreeBSD amd64 64 JDK 32 x86 compiler2 Server VM Client VM
compiler1
1.6.5 IDE
OpenJDK
HotSpot GDB
GDB
VIM HotSpot IDE
GDB HotSpot “ IDE HotSpot

NetBeans http://netbeans.org/ NetBeans


C/C++ “ C/C++ ”
OpenJDK hotspot “ ”
1-8 “ ”

1-8 NetBeans HotSpot 1

“ ” “ makefile” Makefile
hotspot/make 1-9 “ ” “ ”
${MAKE}-f Makefile clean jvmg
ALT_BOOTDIR=/Library/Java/JavaVirtualMachines/jdk1.7.0_04.jdk/Contents/Home ARCH_DATA_MODEL=64 LANG=C

1-9 NetBeans HotSpot 2

OpenJDK 7u4 Makefile 64


NetBeans 32 ARCH_DATA_MODEL
64 ALT_BOOTDIR LANG
“ ” HotSpot NetBeans

HotSpot NetBeans
NetBeans HotSpot
“ ” “ ”

/Users/IcyFenix/Develop/JVM/jdkBuild/openjdk_7u4/hotspot/build/bsd/bsd_amd64_compiler2/jvmg/gamma Queens
Queens Makefile Java
Java

Java Java
HotSpot
JIT
HotSpot

-XX +TraceBytecodes-XX StopInterpreterAt= n

n
gamma

“ ” env.sh
1-10

1-10 NetBeans HotSpot 3

HotSpot
java.c main 1-11

1-11 NetBeans HotSpot 4

HotSpot C/C++
1-3

1-3 HotSpot [1]


[1] RednaxelaFX http://hllvm.group.iteye.com/group/topic/26998
1.7
Java
OpenJDK 7
Java 4 Java Class
2 Java

5
2 Java
Java C++ “ ”

2.1
C C++
“ ” “ ”—— “ ”

Java new
delete/free
Java Java

1 Java
2.2
Java Java

Java Java
SE 7 Java 2-1

2-1 Java

2.2.1
Program Counter Register

Java


Java
Native Undefined
Java OutOfMemoryError
2.2.2 Java
Java Java Virtual Machine Stacks
Java
Stack Frame [1]

Java Heap Stack


Java
“ ”
“ ”

boolean byte char short int


float long double reference

returnAddress

64 long double 2 Slot


1

Java
StackOverflowError
Java Java
OutOfMemoryError

[1] 8
2.2.3
Native Method Stack
Java
Native

Sun HotSpot
StackOverflowError OutOfMemoryError
2.2.4 Java
Java Java Heap Java
Java
Java
[1]
JIT
[2]

“ ”

Java “GC ” Garbage


Collected Heap “ ”
Java
Eden From Survivor To Survivor
Java Thread Local Allocation Buffer,TLAB

Java 3

Java Java

-Xmx -Xms
OutOfMemoryError

[1]Java The heap is the runtime data area from which memory for all class
instances and arrays is allocated
[2] 11
2.2.5
Method Area Java
Java
Non-Heap
Java

HotSpot
“ ” Permanent Generation HotSpot
GC
HotSpot Java
BEA JRockit IBM J9

-XX MaxPermSize J9 JRockit 32


4GB String.intern
HotSpot
Native Memory [1]

JDK 1.7 HotSpot

Java Java

“ ”

“ ”
Sun BUG BUG
HotSpot

Java
OutOfMemoryError

[1]JEP 122-Remove the Permanent Generation http://openjdk.java.net/jeps/122


2.2.6
Runtime Constant Pool Class
Constant Pool Table

Java Class

Java
Class
[1]

Class Java
Class

String intern

OutOfMemoryError

[1] Class 6
2.2.7
Direct Memory Java
OutOfMemoryError

JDK 1.4 NIO New Input/Output Channel


Buffer I/O Native
Java DirectByteBuffer
Java Native

Java
RAM SWAP
-Xmx

OutOfMemoryError
2.3 HotSpot
Java

HotSpot Java HotSpot Java

2.3.1
Java Java
new
Java Class

new

2.3.2
Java Java

“ ” Bump the Pointer Java

“ ” Free List
Java Java
Serial ParNew Compact
CMS Mark-Sweep

A B

—— CAS
Java
Thread Local Allocation Buffer,TLAB
TLAB TLAB TLAB
TLAB -XX +/-UseTLAB

TLAB TLAB
Java

GC
Object Header

Java
—— init
invokespecial new
init

2-1 HotSpot bytecodeInterpreter.cpp


JIT
HotSpot

2-1 HotSpot

//
if constants- tag_at index .is_unresolved_klass {
// klassOop instanceKlassOop
oop entry= klassOop *constants- obj_at_addr index
assert entry- is_klass "Should be resolved klass"
klassOop k_entry= klassOop entry
assert k_entry- klass_part - oop_is_instance "Should be instanceKlass"
instanceKlass * ik= instanceKlass* k_entry- klass_part
//
if ik- is_initialized ik- can_be_fastpath_allocated
{
//
size_t obj_size=ik- size_helper
oop result=NULL
//
bool need_zero= ZeroTLAB
// TLAB
if UseTLAB {
result= oop THREAD- tlab .allocate obj_size
}
if result==NULL {
need_zero=true
// eden
retry
HeapWord * compare_to=*Universe heap - top_addr
HeapWord * new_top=compare_to+obj_size
/*cmpxchg x86 CAS C++ CAS
retry */
if new_top =*Universe heap - end_addr {
if Atomic cmpxchg_ptr new_top,Universe heap - top_addr compare_to =compare_to {
goto retry
}
result= oop compare_to
}
}
if result =NULL {
//
if need_zero {
HeapWord * to_zero= HeapWord* result+sizeof oopDesc /oopSize
obj_size-=sizeof oopDesc /oopSize
if obj_size 0 {
memset to_zero 0 obj_size * HeapWordSize
}
}
//
if UseBiasedLocking {
result- set_mark ik- prototype_header
}else{
result- set_mark markOopDesc prototype
}
result- set_klass_gap 0
result- set_klass k_entry
//
SET_STACK_OBJECT result 0
UPDATE_PC_AND_TOS_AND_CONTINUE 3 1
}
}
}
2.3.2
HotSpot 3 Header
Instance Data Padding

HotSpot
HashCode GC ID
32 64 32bit
64bit “Mark Word” 32
64 Bitmap
Mark Word
32
HotSpot Mark Word 32bit 25bit
4bit 2bit 1bit 0
GC 2-1

2.3.3
Java
Java Java

2-2 HotSpot markOop.cpp 32bit Mark


Word

2-2 markOop.cpp

//Bit-format of an object header most significant first,big endian layout below


//32 bits
//--------
//hash 25------------ |age 4 biased_lock 1 lock 2 normal object
//JavaThread* 23 epoch 2 age 4 biased_lock 1 lock 2 biased object
//size 32------------------------------------------ | CMS free block
//PromotedObject* 29---------- |promo_bits 3----- | CMS promoted object
FieldsAllocationStyle Java
HotSpot longs/doubles ints shorts/chars
bytes/booleans oops Ordinary Object Pointers

CompactFields true true

HotSpot VM 8
8 8 1 2
2.3.3
Java reference
reference Java

Java reference

2-2

2-2

Java
reference 2-3
2-3

reference

reference

Java
Sun HotSpot
2.4 OutOfMemoryError
Java
OutOfMemoryError OOM
2-3 2-9

Java

“VM Args”

Java
Eclipse IDE 2-4 Debug/Run

2-4 Eclipse Debug


Sun HotSpot

2.4.1 Java
Java GC Roots

2-3 Java 20MB -Xms


-Xmx -XX
+HeapDumpOnOutOfMemoryError Dump
[1]

2-3 Java

/**
*VM Args -Xms20m-Xmx20m-XX +HeapDumpOnOutOfMemoryError
*@author zzm
*/
public class HeapOOM{
static class OOMObject{
}
public static void main String[]args {
List OOMObject list=new ArrayList OOMObject
while true {
list.add new OOMObject
}
}
}

java.lang.OutOfMemoryError Java heap space


Dumping heap to java_pid3404.hprof……
Heap dump file created[22045981 bytes in 0.663 secs]

Java OOM Java


“java.lang.OutOfMemoryError” “Java heap space”

Eclipse Memory
Analyzer Dump
Memory Leak Memory
Overflow 2-5 Eclipse Memory Analyzer
2-5 Eclipse Memory Analyzer

GC Roots
GC Roots
GC Roots

-Xmx -Xms

Java
3

[1] 4
2.4.2
HotSpot HotSpot
-Xoss -Xss
Java

StackOverflowError

OutOfMemoryError

OutOfMemoryError StackOverflowError
2-4

-Xss StackOverflowError

StackOverflowError

2-4 OOM 1

/**
*VM Args -Xss128k
*@author zzm
*/
public class JavaVMStackSOF{
private int stackLength=1
public void stackLeak {
stackLength++
stackLeak
}
public static void main String[]args throws Throwable{
JavaVMStackSOF oom=new JavaVMStackSOF
try{
oom.stackLeak
}catch Throwable e {
System.out.println "stack length "+oom.stackLength
throw e
}
}
}

stack length 2402


Exception in thread"main"java.lang.StackOverflowError
at org.fenixsoft.oom.VMStackSOF.leak VMStackSOF.java 20
at org.fenixsoft.oom.VMStackSOF.leak VMStackSOF.java 21
at org.fenixsoft.oom.VMStackSOF.leak VMStackSOF.java 21
……

StackOverflowError

2-5
32 Windows
2GB Java
2GB Xmx MaxPermSize

“ ”

StackOverflowError

1000 2000
64

“ ”

2-5

/**
*VM Args -Xss2M
*@author zzm
*/
public class JavaVMStackOOM{
private void dontStop {
while true {
}
}
public void stackLeakByThread {
while true {
Thread thread=new Thread new Runnable {
@Override
public void run {
dontStop
}
}
thread.start
}
}
public static void main String[]args throws Throwable{
JavaVMStackOOM oom=new JavaVMStackOOM
oom.stackLeakByThread
}
}

Windows Java [1]

Exception in thread"main"java.lang.OutOfMemoryError unable to create new native thread

[1] 12
2.4.3

JDK 1.7 “ ”

String.intern Native
String String String
String JDK 1.6
-XX PermSize -XX MaxPermSize
2-6

2-6

/**
*VM Args -XX PermSize=10M-XX MaxPermSize=10M
*@author zzm
*/
public class RuntimeConstantPoolOOM{
public static void main String[]args {
// List Full GC
List String list=new ArrayList String
//10MB PermSize integer OOM
int i=0
while true {
list.add String.valueOf i++ .intern
}
}
}

Exception in thread"main"java.lang.OutOfMemoryError PermGen space


at java.lang.String.intern Native Method
at org.fenixsoft.oom.RuntimeConstantPoolOOM.main RuntimeConstantPoolOOM.java 18

OutOfMemoryError
“PermGen space” HotSpot

JDK 1.7 while


2-7

2-7 String.intern

public class RuntimeConstantPoolOOM{


public static void main String[]args {
public static void main String[]args {
String str1=new StringBuilder " " .append " " .toString
System.out.println str1.intern ==str1
String str2=new StringBuilder "ja" .append "va" .toString
System.out.println str2.intern ==str2
}
}
}

JDK 1.6 false JDK 1.7 true


false JDK 1.6 intern
StringBuilder
Java false JDK 1.7
JRockit intern
intern StringBuilder str2
false “java” StringBuilder.toString
“ ” “ ”
true

Class

Java SE API GeneratedConstructorAccessor


2-8 CGLib[1]

Spring Hibernate
CGLib
Class JVM Groovy
2-8

2-8 CGLib

/**
*VM Args -XX PermSize=10M-XX MaxPermSize=10M
*@author zzm
*/
public class JavaMethodAreaOOM{
public static void main String[]args {
while true {
Enhancer enhancer=new Enhancer
enhancer.setSuperclass OOMObject.class
enhancer.setUseCache false
enhancer.setCallback new MethodInterceptor {
public Object intercept Object obj,Method method,Object[]args,MethodProxy proxy throws Throwable{
return proxy.invokeSuper obj,args
}
}
enhancer.create
}
}
static class OOMObject{
}
}

Caused by java.lang.OutOfMemoryError PermGen space


at java.lang.ClassLoader.defineClass1 Native Method
at java.lang.ClassLoader.defineClassCond ClassLoader.java 632
at java.lang.ClassLoader.defineClass ClassLoader.java 616
……8 more

Class
CGLib JSP
JSP JSP Java OSGi

[1]CGLib http://cglib.sourceforge.net/
2.4.4
DirectMemory -XX MaxDirectMemorySize Java
-Xmx 2-9 DirectByteBuffer
Unsafe Unsafe getUnsafe
rt.jar Unsafe
DirectByteBuffer

unsafe.allocateMemory

2-9 unsafe

/**
*VM Args -Xmx20M-XX MaxDirectMemorySize=10M
*@author zzm
*/
public class DirectMemoryOOM{
private static final int_1MB=1024*1024
public static void main String[]args throws Exception{
Field unsafeField=Unsafe.class.getDeclaredFields [0]
unsafeField.setAccessible true
Unsafe unsafe= Unsafe unsafeField.get null
while true {
unsafe.allocateMemory _1MB
}
}
}

Exception in thread"main"java.lang.OutOfMemoryError
at sun.misc.Unsafe.allocateMemory Native Method
at org.fenixsoft.oom.DMOOM.main DMOOM.java 20

DirectMemory Heap Dump


OOM Dump NIO
2.5

Java
3 Java
3
Java C++ “ ”

3.1
Garbage Collection,GC Java
GC Java 1960 MIT Lisp
Lisp GC 3

“ ” GC

“ ”

Java 2 Java
3

JIT

Java

“ ”
3.2
Java
“ ” “ ”

3.2.1

1 1 0

Reference Counting

COM Component Object Model ActionScript 3 FlashPlayer Python


Squirrel
Java

3-1 testGC objA objB


instance objA.instance=objB objB.instance=objA

0 GC

3-1

/**
*testGC objA objB GC
*@author zzm
*/
public class ReferenceCountingGC{
public Object instance=null
private static final int_1MB=1024*1024
/**
* GC
*/
private byte[]bigSize=new byte[2*_1MB]
public static void testGC {
ReferenceCountingGC objA=new ReferenceCountingGC
ReferenceCountingGC objB=new ReferenceCountingGC
objA.instance=objB
objB.instance=objA
objA=null
objB=null
// GC,objA objB
System.gc
}
}

[F u l l G C S y s t e m [T e n u r e d 0 K- 2 1 0 K 1 0 2 4 0 K 0.0 1 4 9 1 4 2 s e c s]4603K- 210K 19456K [Perm 2999K-


2999K 21248K ] 0.0150007 secs][Times user=0.01 sys=0.00 real=0.02 secs]
Heap
def new generation total 9216K,used 82K[0x00000000055e0000 0x0000000005fe0000 0x0000000005fe0000
Eden space 8192K 1%used[0x00000000055e0000 0x00000000055f4850 0x0000000005de0000
from space 1024K 0%used[0x0000000005de0000 0x0000000005de0000 0x0000000005ee0000
to space 1024K 0%used[0x0000000005ee0000 0x0000000005ee0000 0x0000000005fe0000
tenured generation total 10240K,used 210K[0x0000000005fe0000 0x00000000069e0000 0x00000000069e0000
the space 10240K 2%used[0x0000000005fe0000 0x0000000006014a18 0x0000000006014c00 0x00000000069e0000
compacting perm gen total 21248K,used 3016K[0x00000000069e0000 0x0000000007ea0000 0x000000000bde0000
the space 21248K 14%used[0x00000000069e0000 0x0000000006cd2398 0x0000000006cd2400 0x0000000007ea0000
No shared spaces configured.
GC “4603K- 210K”
3.2.2
Java C# Lisp
Reachability Analysis
“GC Roots”
Reference Chain GC Roots
GC Roots
3-1 object 5 object 6 object 7 GC Roots

3-1

Java GC Roots

JNI Native
3.2.3

“ ” JDK 1.2 Java


reference

“ ”

JDK 1.2 Java Strong


Reference Soft Reference Weak Reference Phantom
Reference 4 4

“Object obj=new Object ”

JDK 1.2 SoftReference

JDK 1.2 WeakReference

JDK 1.2 PhantomReference


3.2.4
“ ”
“ ”
GC Roots
finalize finalize
finalize “ ”

finalize
F-Queue Finalizer
“ ”
finalize
F-Queue
finalize GC F-Queue
finalize ——
this
“ ”
3-2 finalize

3-2

/**
*
*1. GC
*2. finalize
*@author zzm
*/
public class FinalizeEscapeGC{
public static FinalizeEscapeGC SAVE_HOOK=null
public void isAlive {
System.out.println "yes,i am still alive "
}
@Override
protected void finalize throws Throwable{
super.finalize
System.out.println "finalize mehtod executed "
FinalizeEscapeGC.SAVE_HOOK=this
}
public static void main String[]args throws Throwable{
SAVE_HOOK=new FinalizeEscapeGC
//
SAVE_HOOK=null
System.gc
// finalize 0.5
Thread.sleep 500
if SAVE_HOOK =null {
SAVE_HOOK.isAlive
}else{
System.out.println "no,i am dead "
}
//
SAVE_HOOK=null
System.gc
// finalize 0.5
Thread.sleep 500
if SAVE_HOOK =null {
SAVE_HOOK.isAlive
}else{
System.out.println "no,i am dead "
}
}
}

finalize mehtod executed


yes,i am still alive
no,i am dead

3-2 SAVE_HOOK finalize GC


finalize
finalize

finalize

C/C++ Java C/C++

“ ”
finalize try-finally
Java
3.2.5
HotSpot Java

“ ”
70% 95%

Java “abc”
String “abc”
String “abc”
“abc”

“ ” “ ”
3 “ ”

Java

ClassLoader

java.lang.Class

3 “ ”
HotSpot -Xnoclassgc
-verbose class -XX +TraceClassLoading -XX
+TraceClassUnLoading -verbose class -XX
+TraceClassLoading Product -XX +TraceClassUnLoading
FastDebug

CGLib ByteCode JSP OSGi


ClassLoader
3.3

3.3.1 -
“ - ” Mark-Sweep
“ ” “ ”

— 3-2

3-2 “ - ”
3.3.2
“ ” Copying

3-3

3-3

IBM
98% “ ” 1:1
Eden Survivor Eden Survivor
[1]

Eden Survivor Survivor


Eden Survivor HotSpot Eden Survivor
8:1 90% 80%+10% 10%
“ ” 98%
10% Survivor
Handle Promotion

98%

Survivor
[1] HotSpot IBM
IBM
3.3.3 -

50%
100%

“ - ” Mark-Compact
“ - ”
“ - ”
3-4

3-4 “ - ”
3.3.4
“ ” Generational Collection
Java

“ — ” “ — ”
3.4 HotSpot
3.2 3.3 HotSpot

3.4.1
GC Roots GC Roots

GC
—— “ ”

GC
Java Sun “Stop The World”
CMS

Java GC 1 Exact VM
Classic VM

HotSpot OopMap
HotSpot JIT
GC
3-3 HotSpot Client VM String.hashCode
0x026eb7a9 call OopMap EBX
16 Ordinary Object Pointer
call 0x026eb730 +142 OopMap
=0x026eb7be hlt

3-3 String.hashCode

[Verified Entry Point]


0x026eb730 mov%eax -0x8000 %esp
……
ImplicitNullCheckStub slow case
0x026eb7a9 call 0x026e83e0
OopMap{ebx=Oop[16]=Oop off=142}
*caload
-java.lang.String hashCode@48 line 1489
{runtime_call}
0x026eb7ae push$0x83c5c18
{external_word}
0x026eb7b3 call 0x026eb7b8
0x026eb7b8 pusha
0x026eb7b9 call 0x0822bec0 {runtime_call}
0x026eb7be hlt
3.4.2
OopMap HotSpot GC Roots
OopMap
OopMap GC

HotSpot OopMap “
” Safepoint
GC Safepoint
GC
“ ” ——


Safepoint

Sefepoint GC
JNI “ ”
Preemptive Suspension Voluntary Suspension
GC
“ ”
GC

GC

3-4 test HotSpot 0x160100


test

3-4

0x01b6d627 call 0x01b2b210 OopMap{[60]=Oop off=460}


*invokeinterface size
-Client1 main@113 line 23
{virtual_call}
0x01b6d62c nop
OopMap{[60]=Oop off=461}
*if_icmplt
-Client1 main@118 line 23
0x01b6d62d test%eax 0x160100 {poll}
0x01b6d633 mov 0x50 %esp %esi
0x01b6d637 cmp%eax %esi
3.4.3
Safepoint GC
Safepoint GC Safepoint
“ ” CPU
Sleep Blocked JVM “ ”
JVM CPU
Safe Region

GC Safe Region Safepoint

Safe Region Safe Region


JVM GC Safe Region
Safe Region GC
Safe Region

HotSpot
GC
GC HotSpot GC
3.5
Java

JDK 1.7 Update 14


HotSpot G1 G1
3-5

3-5 HotSpot [1]

3-5 7

CMS G1

HotSpot

3.5.1 Serial
Serial JDK 1.3.1

“ ” CPU
“Stop
The World”

5
3-6 Serial/Serial Old

3-6 Serial/Serial Old

“Stop The World”



JDK 1.3 JDK 1.7 HotSpot


Serial Parallel
Concurrent Mark Sweep CMS GC Garbage First G1

RTSJ

Serial “ ”
Client

CPU Serial

Serial Client

[1] http://blogs.sun.com/jonthecollector/entry/our_collectors
3.5.2 ParNew
ParNew Serial
Serial -XX SurvivorRatio -XX
PretenureSizeThreshold -XX HandlePromotionFailure Stop The World
Serial
ParNew 3-7

3-7 ParNew/Serial Old

ParNew Serial
Server
Serial CMS JDK 1.5
HotSpot ——CMS
Concurrent Mark Sweep HotSpot
Concurrent

CMS JDK 1.4.0


Parallel Scavenge [1]
JDK 1.5 CMS
ParNew Serial ParNew -XX +UseConcMarkSweepGC
-XX +UseParNewGC

ParNew CPU Serial


CPU
Serial CPU GC
CPU CPU
32 CPU 4 32 CPU
-XX ParallelGCThreads

ParNew

● Parallel
● Concurrent
CPU

[1]Parallel Scavenge G1 GC

http://blogs.sun.com/jonthecollector/entry/our_collectors
3.5.3 Parallel Scavenge
Parallel Scavenge
…… ParNew

Parallel Scavenge CMS


Parallel Scavenge
Throughput CPU CPU
= / +
100 1 99%

CPU

Parallel Scavenge
-XX MaxGCPauseMillis -XX GCTimeRatio

MaxGCPauseMillis 0

GC
300MB 500MB
10 100 5
70

GCTimeRatio 0 100
19 GC
5% 1/ 1+19 99 1% 1/ 1+99

Parallel Scavenge “ ”
Parallel Scavenge -XX +UseAdaptiveSizePolicy
-Xmn
Eden Survivor -XX SurvivorRatio -XX
PretenureSizeThreshold
GC
GC Ergonomics [1]

Parallel Scavenge
-Xmx
MaxGCPauseMillis GCTimeRatio

Parallel Scavenge ParNew

[1] http://download.oracle.com/javase/1.5.0/docs/guide/vm/gc-ergonomics.html
3.5.4 Serial Old
Serial Old Serial “ -
” Client Server
JDK 1.5 Parallel Scavenge
[1]
CMS Concurrent
Mode Failure Serial Old
3-8

3-8 Serial/Serial Old


[1] Parallel Scavenge PS MarkSweep
Serial Old PS MarkSweep Serial Old
Serial Old PS MarkSweep
3.5.5 Parallel Old
Parallel Old Parallel Scavenge “ - ”
JDK 1.6 Parallel Scavenge
Parallel Scavenge
Serial Old PS MarkSweep Parallel Scavenge
CMS Serial Old “
” Parallel Scavenge
CPU
ParNew CMS “ ”

Parallel Old “ ”
CPU Parallel Scavenge Parallel Old
Parallel Old 3-9

3-9 Parallel Scavenge/Parallel Old


3.5.6 CMS
CMS Concurrent Mark Sweep
Java B/S
CMS

“Mark Sweep” CMS “ — ”


4

CMS initial mark

CMS concurrent mark

CMS remark

CMS concurrent sweep

“Stop The World”


GC Roots GC RootsTracing

CMS
3-10 CMS

3-10 Concurrent Mark Sweep

CMS
Sun Concurrent Low Pause
Collector CMS 3

CMS CPU CPU


CPU
CMS CPU
+3 /4 CPU 4 25% CPU
CPU CPU 4 2 CMS
CPU
50%
“ ” Incremental Concurrent Mark Sweep/i-CMS
CMS CPU PC
GC GC

CMS
i-CMS “deprecated”

CMS Floating Garbage “Concurrent Mode


Failure” Full GC CMS
CMS
GC “

CMS
JDK 1.5
CMS 68%
-XX CMSInitiatingOccupancyFraction
JDK 1.6 CMS
92% CMS
“Concurrent Mode Failure” Serial Old
-XX CM
SInitiatingOccupancyFraction “Concurrent Mode Failure”

CMS “ — ”

Full
GC CMS -XX +UseCMSCompactAtFullCollection
CMS FullGC

-XX CMSFullGCsBeforeCompaction
Full GC 0 Full
GC
3.5.7 G1
G1 Garbage-First JDK 1.7
Sun JDK 1.7 RoadMap JDK 1.7 HotSpot
JDK 6u14 Early Access G1
G1 “Experimental” JDK 7u4 Sun
“Experimental”

G1 HotSpot
JDK 1.5 CMS GC G1

G1 CPU CPU CPU


CPU Stop-The-World Java
GC G1 Java

G1 G1
GC
GC

CMS “ — ” G1 “ — ”
Region “ ”
G1

GC

G1 CMS G1 CMS
G1
M N
Java RTSJ

G1 G1
G1 Java Java
Region
Region

G1 Java
G1 Region

Region Garbage-First Region


G1

G1 “ ”
2004 Sun G1 10
G1 Java Region
Region
Region Region Region
Java
Java G1
G1

Minor GC

G1 Region
Remembered Set G1 Region
Remembered Set Reference
Write Barrier Reference Region

CardTable Region Remembered Set


GC Remembered Set

Remembered Set G1

Initial Marking

Concurrent Marking

Final Marking

Live Data Counting and Evacuation

CMS G1 CMS
GC Roots
TAMS Next Top at Mark Start
Region GC Root

Remembered Set Logs


Remembered Set Logs Remembered Set
Region
GC Sun
Region
3-11 G1
3-11 G1

G1 G1
G1
“ ”
Java Microbenchmark Java -XX
+PrintGCDetails GC G1
Sun Garbage-First Garbage Collection

Sun Benchmark Sun V880 8×750MHz UltraSPARC III CPU


32G Solaris 10 SPECjbb
165MB telco
100MB
ParNew+CMS CPU
8 GC

Soft Real-Time Goal


X/Y Y GC X
CMS
Java V% avgV% wV%

V%
GC GC

avgV% GC GC GC
GC GC

wV% GC

3-1
3-1 telco 0.5% 0.7%
SPECjbb 2% 5% X/Y
GC
100/200 512MB G1 100% GC
CMS 3 Java 100%
GC

3 SPECjbb 15 telco 3-12


SPECjbb G1
GC telco
CMS SPECjbb 768MB CMS
5% 10% telco CMS 3% 4%
3-12

StackOverflow.com
“ G1 60 70GB
20 50GB Linux JDK 6u22 G1 PS/PS Old
PS GC
50 GC -XX MaxGCPauseMillis=50 65GB Java
30 2 Stop-The-World G1 CMS
CMS Oracle G1
G1
G1 G1
G1 ”
3.5.8 GC
GC Java
1 GC
GC

GC

33.125 [GC[DefNew 3324K- 152K 3712K 0.0025925 secs]3324K- 152K 11904K 0.0031680 secs]
1 0 0.6 6 7 [F u l l G C[T e n u r e d 0 K- 2 1 0 K 1 0 2 4 0 K 0.0 1 4 9 1 4 2 s e c s]4603K- 210K 19456K [Perm 2999K-
2999K 21248K ] 0.0150007 secs][Times user=0.01 sys=0.00 real=0.02 secs]

“33.125 ” “100.667 ” GC Java

GC “[GC” “[Full GC”


GC GC “Full” GC Stop-The-World
ParNew “[Full GC”
STW System.gc
“[Full GC System ”

[Full GC 283.736 [ParNew 261599K- 261599K 261952K 0.0000288 secs]

“[DefNew” “[Tenured” “[Perm” GC


GC Serial “Default
New Generation” “[DefNew” ParNew
“[ParNew” “Parallel New Generation” Parallel Scavenge
“PSYoungGen”

“3324K- 152K 3712K ” “GC -


GC ” “3324K-
152K 11904K ” “GC Java - GC Java Java

“0.0025925 secs” GC
“[Times user=0.01 sys=0.00 real=0.02 secs]” user
sys real Linux time CPU
CPU Wall Clock Time CPU
I/O
CPU CPU
CPU user sys real
3.5.9
JDK 1.7
3-2
3.6
Java

JIT
[1]
Eden
TLAB

Client
Serial/Serial Old ParNew/Serial Old

3.6.1 Eden
Eden Eden
Minor GC

-XX +PrintGCDetails

3-5 testAllocation 3 2MB 14MB


-Xms20M -Xmx20M -Xmn10M 3 Java 20MB
10MB 10MB -XX SurvivorRatio=8
Eden Survivor 8:1 “eden
space 8192K from space 1024K to space 1024K”
9216KB Eden +1 Survivor

testAllocation allocation4 Minor GC GC


6651KB 148KB allocation1
allocation2 allocation3
GC allocation4 Eden 6MB
allocation4 4MB Minor GC GC 3
2MB Survivor Survivor 1MB

GC 4MB allocation4 Eden


Eden 4MB allocation4 Survivor 6MB allocation1
allocation2 allocation3 GC

Minor GC Full GC

GC Minor GC Java
Minor GC

GC Major GC/Full GC GC Major GC


Minor GC Parallel Scavenge
Major GC Major GC Minor GC 10

3-5 Minor GC

private static final int_1MB=1024*1024


/**
*VM -verbose gc-Xms20M-Xmx20M-Xmn10M-XX +PrintGCDetails
-XX SurvivorRatio=8
*/
public static void testAllocation {
byte[]allocation1 allocation2 allocation3 allocation4
allocation1=new byte[2*_1MB]
allocation2=new byte[2*_1MB]
allocation3=new byte[2*_1MB]
allocation4=new byte[4*_1MB] // Minor GC
}

[GC[DefNew 6651K- 148K 9216K 0.0070106 secs]6651K- 6292K 19456K


0.0070426 secs][Times user=0.00 sys=0.00 real=0.00 secs]
Heap
def new generation total 9216K,used 4326K[0x029d0000 0x033d0000 0x033d0000
eden space 8192K 51%used[0x029d0000 0x02de4828 0x031d0000
from space 1024K 14%used[0x032d0000 0x032f5370 0x033d0000
to space 1024K 0%used[0x031d0000 0x031d0000 0x032d0000
tenured generation total 10240K,used 6144K[0x033d0000 0x03dd0000 0x03dd0000
the space 10240K 60%used[0x033d0000 0x039d0030 0x039d0200 0x03dd0000
compacting perm gen total 12288K,used 2114K[0x03dd0000 0x049d0000 0x07dd0000
the space 12288K 17%used[0x03dd0000 0x03fe0998 0x03fe0a00 0x049d0000
No shared spaces configured.

[1]JIT 11
3.6.2
Java
byte[]
Java
“ ” “ ”
“ ”

-XX PretenureSizeThreshold
Eden Survivor

3-6 testPretenureSizeThreshold Eden


10MB 40% 4MB allocation
PretenureSizeThreshold 3MB 3145728 -Xmx
3MB 3MB
PretenureSizeThreshold Serial ParNew Parallel Scavenge
Parallel Scavenge
ParNew CMS

3-6

private static final int_1MB=1024*1024


/**
*VM -verbose gc-Xms20M-Xmx20M-Xmn10M-XX +PrintGCDetails-XX SurvivorRatio=8
*-XX PretenureSizeThreshold=3145728
*/
public static void testPretenureSizeThreshold {
byte[]allocation
allocation=new byte[4*_1MB] //
}

Heap
def new generation total 9216K,used 671K[0x029d0000 0x033d0000 0x033d0000
eden space 8192K 8%used[0x029d0000 0x02a77e98 0x031d0000
from space 1024K 0%used[0x031d0000 0x031d0000 0x032d0000
to space 1024K 0%used[0x032d0000 0x032d0000 0x033d0000
tenured generation total 10240K,used 4096K[0x033d0000 0x03dd0000 0x03dd0000
the space 10240K 40%used[0x033d0000 0x037d0010 0x037d0200 0x03dd0000
compacting perm gen total 12288K,used 2107K[0x03dd0000 0x049d0000 0x07dd0000
the space 12288K 17%used[0x03dd0000 0x03fdefd0 0x03fdf000 0x049d0000
No shared spaces configured.
3.6.3

Age Eden Minor GC


Survivor Survivor 1 Survivor
“ ” Minor GC 1 15
-XX
MaxTenuringThreshold

-XX MaxTenuringThreshold=1 -XX MaxTenuringThreshold=15


3-7 testTenuringThreshold allocation1
256KB Survivor MaxTenuringThreshold=1 allocation1
GC GC 0KB
MaxTenuringThreshold=15 GC allocation1 Survivor
404KB

3-7

private static final int_1MB=1024*1024


/**
*VM -verbose gc-Xms20M-Xmx20M-Xmn10M-XX +PrintGCDetails-XX SurvivorRatio=8-XX MaxTenuringThreshold=1
*-XX +PrintTenuringDistribution
*/
@SuppressWarnings "unused"
public static void testTenuringThreshold {
byte[]allocation1 allocation2 allocation3
allocation1=new byte[_1MB/4]
// XX MaxTenuringThreshold
allocation2=new byte[4*_1MB]
allocation3=new byte[4*_1MB]
allocation3=null
allocation3=new byte[4*_1MB]
}

MaxTenuringThreshold=1

[GC[DefNew
Desired Survivor size 524288 bytes,new threshold 1 max 1
-age 1 414664 bytes 414664 total
4859K- 404K 9216K 0.0065012 secs]4859K- 4500K 19456K 0.0065283 secs][Times user=0.02 sys=0.00 real=0.02 secs]
[GC[DefNew
Desired Survivor size 524288 bytes,new threshold 1 max 1
4500K- 0K 9216K 0.0009253 secs]8596K- 4500K 19456K 0.0009458 secs][Times user=0.00 sys=0.00 real=0.00 secs]
Heap
def new generation total 9216K,used 4178K[0x029d0000 0x033d0000 0x033d0000
eden space 8192K 51%used[0x029d0000 0x02de4828 0x031d0000
from space 1024K 0%used[0x031d0000 0x031d0000 0x032d0000
to space 1024K 0%used[0x032d0000 0x032d0000 0x033d0000
tenured generation total 10240K,used 4500K[0x033d0000 0x03dd0000 0x03dd0000
the space 10240K 43%used[0x033d0000 0x03835348 0x03835400 0x03dd0000
compacting perm gen total 12288K,used 2114K[0x03dd0000 0x049d0000 0x07dd0000
the space 12288K 17%used[0x03dd0000 0x03fe0998 0x03fe0a00 0x049d0000
No shared spaces configured.
MaxTenuringThreshold=15
[GC[DefNew
Desired Survivor size 524288 bytes,new threshold 15 max 15
-age 1 414664 bytes 414664 total
4859K- 404K 9216K 0.0049637 secs]4859K- 4500K 19456K 0.0049932 secs][Times user=0.00 sys=0.00 real=0.00 secs]
[GC[DefNew
Desired Survivor size 524288 bytes,new threshold 15 max 15
-age 2 414520 bytes 414520 total
4500K- 404K 9216K 0.0008091 secs]8596K- 4500K 19456K 0.0008305 secs][Times user=0.00 sys=0.00 real=0.00 secs]
Heap
def new generation total 9216K,used 4582K[0x029d0000 0x033d0000 0x033d0000
eden space 8192K 51%used[0x029d0000 0x02de4828 0x031d0000
from space 1024K 39%used[0x031d0000 0x03235338 0x032d0000
to space 1024K 0%used[0x032d0000 0x032d0000 0x033d0000
tenured generation total 10240K,used 4096K[0x033d0000 0x03dd0000 0x03dd0000
the space 10240K 40%used[0x033d0000 0x037d0010 0x037d0200 0x03dd0000
compacting perm gen total 12288K,used 2114K[0x03dd0000 0x049d0000 0x07dd0000
the space 12288K 17%used[0x03dd0000 0x03fe0998 0x03fe0a00 0x049d0000
No shared spaces configured.
3.6.4

MaxTenuringThreshold Survivor
Survivor
MaxTenuringThreshold

3-8 testTenuringThreshold2 -XX


MaxTenuringThreshold=15 Survivor 0%
6% allocation1 allocation2 15
512KB
Survivor new

3-8

private static final int_1MB=1024*1024


/**
*VM -verbose gc-Xms20M-Xmx20M-Xmn10M-XX +PrintGCDetails-XX SurvivorRatio=8-XX MaxTenuringThreshold=15
*-XX +PrintTenuringDistribution
*/
@SuppressWarnings "unused"
public static void testTenuringThreshold2 {
byte[]allocation1 allocation2 allocation3 allocation4
allocation1=new byte[_1MB/4]
//allocation1+allocation2 survivo
allocation2=new byte[_1MB/4]
allocation3=new byte[4*_1MB]
allocation4=new byte[4*_1MB]
allocation4=null
allocation4=new byte[4*_1MB]
}

[GC[DefNew
Desired Survivor size 524288 bytes,new threshold 1 max 15
-age 1 676824 bytes 676824 total
5115K- 660K 9216K 0.0050136 secs]5115K- 4756K 19456K 0.0050443 secs][Times user=0.00 sys=0.01 real=0.01 secs]
[GC[DefNew
Desired Survivor size 524288 bytes,new threshold 15 max 15
4756K- 0K 9216K 0.0010571 secs]8852K- 4756K 19456K 0.0011009 secs][Times user=0.00 sys=0.00 real=0.00 secs]
Heap
def new generation total 9216K,used 4178K[0x029d0000 0x033d0000 0x033d0000
eden space 8192K 51%used[0x029d0000 0x02de4828 0x031d0000
from space 1024K 0%used[0x031d0000 0x031d0000 0x032d0000
to space 1024K 0%used[0x032d0000 0x032d0000 0x033d0000
tenured generation total 10240K,used 4756K[0x033d0000 0x03dd0000 0x03dd0000
the space 10240K 46%used[0x033d0000 0x038753e8 0x03875400 0x03dd0000
compacting perm gen total 12288K,used 2114K[0x03dd0000 0x049d0000 0x07dd0000
the space 12288K 17%used[0x03dd0000 0x03fe09a0 0x03fe0a00 0x049d0000
No shared spaces configured.
3.6.5
Minor GC
Minor GC
HandlePromotionFailure

Minor GC Minor GC HandlePromotionFailure


Full GC

“ ”
Survivor Minor
GC
Survivor

Full GC

Minor GC
Handle Promotion Failure
HandlePromotionFailure Full GC
HandlePromotionFailure
Full GC 3-9 JDK 6 Update 24

3-9

private static final int_1MB=1024*1024


/**
*VM -Xms20M-Xmx20M-Xmn10M-XX +PrintGCDetails-XX SurvivorRatio=8-XX -HandlePromotionFailure
*/
@SuppressWarnings "unused"
public static void testHandlePromotion {
byte[]allocation1 allocation2 allocation3 allocation4 allocation5 allocation6 allocation7
allocation1=new byte[2*_1MB]
allocation2=new byte[2*_1MB]
allocation3=new byte[2*_1MB]
allocation1=null
allocation4=new byte[2*_1MB]
allocation5=new byte[2*_1MB]
allocation6=new byte[2*_1MB]
allocation4=null
allocation5=null
allocation6=null
allocation7=new byte[2*_1MB]
}

HandlePromotionFailure=false

[GC[DefNew 6651K- 148K 9216K 0.0078936 secs]6651K- 4244K 19456K 0.0079192 secs][Times user=0.00 sys=0.02 real=0.02 secs]
[G C[D e f N e w 6 3 7 8 K- 6 3 7 8 K 9 2 1 6 K 0.0 0 0 0 2 0 6 s e c s][T e n u r e d 4096K- 4244K 10240K 0.0042901 secs]10474K-
4244K 19456K [Perm 2104K- 2104K 12288K ] 0.0043613 secs][Times user=0.00 sys=0.00 real=0.00 secs]

HandlePromotionFailure=true

[GC[DefNew 6651K- 148K 9216K 0.0054913 secs]6651K- 4244K 19456K 0.0055327 secs][Times user=0.00 sys=0.00 real=0.00 secs]
[GC[DefNew 6378K- 148K 9216K 0.0006584 secs]10474K- 4244K 19456K 0.0006857 secs][Times user=0.00 sys=0.00 real=0.00 secs]

JDK 6 Update 24 HandlePromotionFailure


OpenJDK 3-10
HandlePromotionFailure JDK 6 Update
24
Minor GC Full GC

3-10 HotSpot

bool TenuredGeneration promotion_attempt_is_safe size_t


max_promotion_in_bytes const{
//
size_t available=max_contiguous_available
//
size_t av_promo= size_t gc_stats - avg_promoted - padded_average
// GC
bool res= available =av_promo || available =
max_promotion_in_bytes
return res
}
3.7
JDK 1.7
Java
4
Java C++ “ ”

4.1

GC
threaddump/javacore heapdump/hprof

“ ”
4.2 JDK
Java JDK bin “java.exe” “javac.exe”
JDK bin JDK
bin bin 4-1

Sun “ ” JDK
“ ” unsupported and experimental [1]

4-1 Sun JDK

JDK
4-1 “ ”
27KB JDK
jdk/lib/tools.jar
tools 4-1 4-2
Linux JDK Shell
vim

JDK Java
Telnet
tools.jar [2]

4-2 tools.jar

Windows JDK 1.6 Update 21


JDK JDK 1.5
JDK 1.6
JDK 1.6 JDK 1.5
4-1 JDK

JDK 1.5
“-Dcom.sun.management.jmxremote” JMX
JMX 4.3 JDK
1.6 JMX
4.2.1 jps
JDK UNIX jps JVM Process Status
Tool UNIX ps ps
Main Class,main
ID Local Virtual Machine Identifier,LVMID
JDK JDK
LVMID LVMID
ID Process Identifier,PID Windows UNIX ps
LVMID
jps

jsp

jps[options][hostid]

jps

D \Develop\Java\jdk1.6.0_21\bin jps-l
2388 D \Develop\glassfish\bin\..\modules\admin-cli.jar
2764 com.sun.enterprise.glassfish.bootstrap.ASMain
3788 sun.tools.jps.Jps

jps RMI RMI hostid RMI


jps 4-2
[1]http://download.oracle.com/javase/6/docs/technotes/tools/index.html
[2]tools.jar Java API
Sun Hotspot Sun JDK License IBM J9 BEA
JRockit tools.jar
4.2.2 jstat
jstat JVM Statistics Monitoring Tool
[1]
JIT
GUI

jstat

jstat[option vmid[interval[s|ms][count]]]

VMID LVMID VMID


LVMID VMID

[protocol ][//]lvmid[@hostname[ port]/servername]

interval count
250 2764 20

jstat-gc 2764 250 20

option 3
4-3
jstat
GlassFish v3
4-1

4-1 jstat

D \Develop\Java\jdk1.6.0_21\bin jstat-gcutil 2764


S0 S1 E O P YGC YGCT FGC FGCT GCT
0.00 0.00 6.20 41.42 47.20 16 0.105 3 0.472 0.577

Eden E Eden 6.2%


Survivor S0 S1 Survivor0 Survivor1 O Old
P Permanent 41.42% 47.20%
Minor GC YGC Young GC 16 0.105 Full GC FGC Full
GC 3 Full GC FGCT Full GC Time 0.472 GC GCT
GC Time 0.577

jstat
VisualVM
jstat

[1] RMI Sun jstatd RMI


4.2.3 jinfo Java
jinfo Configuration Info for Java jps
-v
jinfo -flag
JDK 1.6 java-XX +PrintFlagsFinal
jinfo -sysprops System.getProperties
JDK 1.5 Linux JDK
JDK 1.6 jinfo Windows Linux
-flag[+|-]name -flag name=value
JDK 1.6 jinfo Windows -flag

jinfo

jinfo[option]pid

CMSInitiatingOccupancyFraction

C \ jinfo-flag CMSInitiatingOccupancyFraction 1444


-XX CMSInitiatingOccupancyFraction=85
4.2.4 jmap Java
jmap Memory Map for Java heapdump dump
jmap Java “ ”
2 -XX +HeapDumpOnOutOfMemoryError OOM
dump -XX +HeapDumpOnCtrlBreak [Ctrl]+[Break]
dump Linux Kill-3 “ ”
dump

jmap dump finalize Java

jinfo jmap Windows dump -


dump -histo
Linux/Solaris

jmap

jmap[option]vmid

option 4-4

4-2 jmap Eclipse dump


3500 jps LVMID

4-2 jmap dump


C \Users\IcyFenix jmap-dump format=b,file=eclipse.bin 3500
Dumping heap to C \Users\IcyFenix\eclipse.bin……
Heap dump file created
4.2.5 jhat
Sun JDK jhat JVM Heap Analysis Tool jmap jmap
jhat HTTP/HTML dump

jhat dump
dump dump
[1]

jhat
VisualVM dump Eclipse Memory
Analyzer IBM HeapAnalyzer [2]
jhat 4-
3 jhat 4.2.4 jmap Eclipse IDE

4-3 jhat dump

C \Users\IcyFenix jhat eclipse.bin


Reading from eclipse.bin……
Dump file created Fri Nov 19 22 07 21 CST 2010
Snapshot read,resolving……
Resolving 1225951 objects……
Chasing references,expect 245 dots……
Eliminating duplicate references……
Snapshot resolved.
Started HTTP server on port 7000
Server is ready.

“Server is ready.” http://localhost 7000/


4-3
4-3 jhat

“Heap Histogram” jmap-histo OQL


SQL
OQL D

[1] dump dump


64 JDK
[2]IBM HeapAnalyzer IBM J9
4.2.6 jstack Java
jstack Stack Trace for Java
threaddump javacore

jstack

jstack

jstack[option]vmid

option 4-5

4-4 jstack Eclipse 3500 jps


LVMID

4-4 jstack

C \Users\IcyFenix jstack-l 3500


2010-11-19 23 11 26
Full thread dump Java HotSpot TM 64-Bit Server VM 17.1-b03 mixed mode
"[ThreadPool Manager]-Idle Thread"daemon prio=6 tid=0x0000000039dd4000 nid=0xf50 in Object.wait [0x000000003c96f000]
java.lang.Thread.State WAITING on object monitor
at java.lang.Object.wait Native Method
-waiting on 0x0000000016bdcc60 a org.eclipse.equinox.internal.util.impl.tpt.threadpool.Executor
at java.lang.Object.wait Object.java 485
at org.eclipse.equinox.internal.util.impl.tpt.threadpool.Executor.run Executor.java 106
-locked 0x0000000016bdcc60 a org.eclipse.equinox.internal.util.impl.tpt.threadpool.Executor
Locked ownable synchronizers
-None

JDK 1.5 java.lang.Thread getAllStackTraces


StackTraceElement jstack

4-5

4-5 JSP

%@page import="java.util.Map"%
html
head
title /title
/head
body
pre
%
for Map.Entry Thread,StackTraceElement[] stackTrace Thread.
getAllStackTraces .entrySet {
Thread thread= Thread stackTrace.getKey
StackTraceElement[]stack= StackTraceElement[] stackTrace.getValue
if thread.equals Thread.currentThread {
continue
}
out.print "\n "+thread.getName +"\n"
for StackTraceElement element stack {
out.print "\t"+element+"\n"
}
}
%
/pre
/body
/html
4.2.7 HSDIS JIT
Java
Sun Sun Classic VM


”——

GDB Windbg
Java JIT
CodeBuffer

——HSDIS

HSDIS Sun HotSpot JIT HotSpot


Project Kenai [1]

HotSpot -XX +PrintAssembly

CPU Project Kenai


JDK_HOME/jre/bin/client JDK_HOME/jre/bin/server
Windows [2]

Debug FastDebug HotSpot


-XX +PrintAssembly Product HotSpot
-XX +UnlockDiagnosticVMOptions 4-6

4-6

public class Bar{


int a=1
static int b=2
public int sum int c {
return a+b+c
}
public static void main String[]args {
new Bar .sum 3
}
}

java-XX +PrintAssembly-Xcomp-XX CompileCommand=dontinline *Bar.sum-XX Compi leCommand=compileonly *Bar.sum test.Bar

-Xcomp “ ”
JIT [3]
-XX CompileCommand
sum sum -XX +PrintAssembly
4-7
4-7

[Disassembling for mach='i386']


[Entry Point]
[Constants]
#{method}'sum'' I I'in'test/Bar'
#this ecx='test/Bar'
#parm0 edx=int
#[sp+0x20] sp of caller
……
0x01cac407 cmp 0x4 %ecx %eax
0x01cac40a jne 0x01c6b050 {runtime_call}
[Verified Entry Point]
0x01cac410 mov%eax -0x8000 %esp
0x01cac417 push%ebp
0x01cac418 sub$0x18 %esp *aload_0
-test.Bar sum@0 line 8
block B0[0 10]
0x01cac41b mov 0x8 %ecx %eax *getfield a
-test.Bar sum@1 line 8
0x01cac41e mov$0x3d2fad8 %esi {oop a
'java/lang/Class'='test/Bar' }
0x01cac423 mov 0x68 %esi %esi *getstatic b
-test.Bar sum@4 line 8
0x01cac426 add%esi %eax
0x01cac428 add%edx %eax
0x01cac42a add$0x18 %esp
0x01cac42d pop%ebp
0x01cac42e test%eax 0x2b0100 {poll_return}
0x01cac434 ret

1 mov%eax -0x8000 %esp

2 push%ebp

3 sub$0x18 %esp

4 mov 0x8 %ecx %eax a 0x8 %ecx ecx+0x8


“[Constants]” “this ecx='test/Bar'” ecx this
0x8 this a “Java ”

5 mov$0x3d2fad8 %esi test.Bar

6 mov 0x68 %esi %esi b “ ”

7 add%esi %eax add%edx %eax a+b+c a


eax b esi c [Constants] “parm0 edx=int” c edx

8 add$0x18 %esp

9 pop%ebp

10 test%eax 0x2b0100 SafePoint

11 ret

[1]Project Kenai http://kenai.com/projects/base-hsdis


[2]HLLVM http://hllvm.group.iteye.com/
[3]-Xcomp HotSpot
JIT
4.3 JDK
JDK JConsole
VisualVM JDK “unsupported and experimental”

JConsole JDK 1.5 VisualVM JDK 1.6


Update7 Sun Oracle [1]

JDK

“ ”

4.3.1 JConsole Java


JConsole Java Monitoring and Management Console JMX
JMX MBean MBean
JMX
JConsole

1. JConsole

JDK/bin “jconsole.exe” JConsole


jps 4-4
“ ”
4-4 JConsole

4-4 Eclipse JConsole MonitoringTest


MonitoringTest “ ” JConsole
“ ” “ ” “ ” “ ” “VM ” “MBean”6
4-5
4-5 JConsole

“ ” “ ”
“ ” “ ” “CPU ”4 “ ” “ ”
“ ”

2.

“ ” jstat Java
4-8
-Xms100m-Xmx100m-XX +UseSerialGC
64KB/50 Java 1000 JConsole “ ”

4-8 JConsole
/**
* OOMObject 64KB
*/
static class OOMObject{
public byte[]placeholder=new byte[64*1024]
}
public static void fillHeap int num throws InterruptedException{
List OOMObject list=new ArrayList OOMObject
for int i=0 i num i++ {
//
Thread.sleep 50
list.add new OOMObject
}
System.gc
}
public static void main String[]args throws Exception{
fillHeap 1000
}

“ ” Eden 4-6

1000 System.gc Eden


Survivor
System.gc

1 Java 100MB -Xmn

2 System.gc 4-6
System.gc
4-6 Eden

1 4-6 Eden 27 328KB -XX SurvivorRadio


Eden Survivor 8:1 27 328KB×125%=34
160KB

2 System.gc List OOMObject list


fillHeap list System.gc
[2]
System.gc fillHeap

3.

“ ” jstat “ ”
jstack jstack
4-9

4-9

/**
*
*/
public static void createBusyThread {
Thread thread=new Thread new Runnable {
@Override
public void run {
while true // 41

}
} "testBusyThread"
thread.start
}
/**
*
*/
public static void createLockThread final Object lock {
Thread thread=new Thread new Runnable {
@Override
public void run {
synchronized lock {
try{
lock.wait
}catch InterruptedException e {
e.printStackTrace
}
}
}
} "testLockThread"
thread.start
}
public static void main String[]args throws Exception{
BufferedReader br=new BufferedReader new InputStreamReader System.in
br.readLine
createBusyThread
br.readLine
Object obj=new Object
createLockThread obj
}

“ ” main 4-7
BufferedReader readBytes System.in Runnable
Runnable readBytes
CPU

4-7 main

testBusyThread 4-8 testBusyThread


MonitoringTest.java 41 41 while true
Runnable
CPU
4-8 testBusyThread

4-9 testLockThread lock notify notifyAll


WAITING

4-9 testLockThread

testLockThread lock notify notifyAll


4-10

4-10

/**
*
*/
static class SynAddRunalbe implements Runnable{
int a,b
public SynAddRunalbe int a,int b {
this.a=a
this.b=b
}
@Override
public void run {
synchronized Integer.valueOf a {
synchronized Integer.valueOf b {
System.out.println a+b
}
}
}
}
public static void main String[]args {
for int i=0 i 100 i++ {
new Thread new SynAddRunalbe 1 2 .start
new Thread new SynAddRunalbe 2 1 .start
}
}

200 1+2 2+1 for

for 2 3
Integer.valueOf [-128 127]
[3]
valueOf
200 Integer.valueOf
synchronized A B
Integer.valueOf 1 B A Integer.valueOf 2

JConsole “ ” “
” 4-10

4-10

4-10 Thread-43 Thread-12 Integer


Thread-12 Integer Thread-43

[1]VisualVM https://visualvm.dev.java.net/
[2] “ ”
Slot
8
[3] java.lang.Integer.IntegerCache.high
4.3.2 VisualVM
VisualVM All-in-One Java Troubleshooting Tool JDK

VisualVM “All-in-One”

Profiling VisualVM JProfiler YourKit Profiling


VisualVM
Agent
JProfiler YourKit

1.VisualVM

VisualVM NetBeans
VisualVM

jps jinfo

CPU GC jstat jstack

dump jmap jhat

dump dump
Bug

plugins ……

VisualVM JDK 1.6 update 7 JDK 1.6


10 JDK 1.4.2 [1]

4-6
VisualVM VisualVM

VisualVM

[2]
*.nbm “ ”→“ ”→“
” nbm
JDK_HOME/lib/visualvm/visualvm VisualVM
“ ”→“ ”
4-11 “ ” VisualVM
4-11 VisualVM

4-
12
4-12 VisualVM

4-13
4-13
4-13 VisualVM

VisualVM “ ” “ ” “ ” “MBeans” JConsole

2.

VisualVM dump

“ ” “ Dump”

“ ” “ ”
“ Dump”

dump [heapdump]
4-14 dump
heapdump “ ” VisualVM
dump dump
“ ” dump
4-14 dump

“ ” dump
System.getProperties “ ”
“ ”
“ ” “ ” “ ”
500 “OQL ” OQL jhat
OQL OQL D

3.

Profiler VisualVM CPU


Profiling

“CPU” “ ”
VisualVM CPU

“ ” 4-15
4-15 CPU

JDK 1.5 Client ——


rt.jar Bug
VisualVM Profiler
Profiling -Xshare off

4-15 Eclipse IDE

4.BTrace

BTrace [3]
“ ” VisualVM
HotSpot HotSwap [4]

VisualVM BTrace
“Trace Application……” BTrace
Java Java 4-16
4-16 BTrace

Java BTrace 1000


4-11

4-11 BTrace

public class BTraceTest{


public int add int a,int b {
return a+b
}
public static void main String[]args throws IOException{
BTraceTest test=new BTraceTest
BufferedReader reader=new BufferedReader new InputStreamReader System.in
for int i=0 i 10 i++ {
reader.readLine
int a= int Math.round Math.random *1000
int b= int Math.round Math.random *1000
System.out.println test.add a,b
}
}
}

VisualVM BTrace TracingScript


4-12

4-12 BTrace

/*BTrace Script Template*/


import com.sun.btrace.annotations.*
import static com.sun.btrace.BTraceUtils.*
@BTrace
public class TracingScript{
@OnMethod
clazz="org.fenixsoft.monitoring.BTraceTest"
method="add"
location=@Location Kind.RETURN
public static void func @Self org.fenixsoft.monitoring.BTraceTest instance,int a,int b @Return int result {
println " "
jstack
println strcat " A " str a
println strcat " B " str b
println strcat " " str result
}
}

“Start” Output “BTrace code


successfuly deployed” Output 4-17

4-17 BTrace

BTrace
BTrace

[1] JDK1.6 -Dcom.sun.management.jmxremote VisualVM


[2] http://Visualvm java.net/pluginscenters.html
[3] http://kenai.com/projects/btrace/
[4]HotSwap HotSpot
4.4
JDK 6

JDK Sun
JDK HotSpot

IBM Support Assistant [1]


Heap Analyzer [2]
Javacore Analyzer [3]
Garbage Collector
Analyzer [4]
IBM J9 VM

HP HPjmeter [5]
HPjtune HP-UX SAP HotSpot VM

Eclipse Memory Analyzer Tool [6]


MAT HP-UX SAP HotSpot VM IBM
DTFJ IBM J9 VM

BEA JRockit Mission Control [7]


JRockit VM

[1]http://www.alphaworks.ibm.com/tech/heapanalyzer/download
[2]http://www.alphaworks.ibm.com/tech/jca/download
[3]http://www.alphaworks.ibm.com/tech/pmat/download
[4]https://h20392.www2.hp.com/portal/swdepot/displayProductInfo.do?
productNumber=HPJMETER
[5]http://www.eclipse.org/mat/
[6]http://www.ibm.com/developerworks/java/jdk/tools/dtfj.html
[7]http://download.oracle.com/docs/cd/E13150_01/jrockit_jvm/jrockit/tools/index.html
5
Java C++ “ ”

5.1
Java

Java


5.2

5.2.1
15 PV/ 4
CPU 16GB 64 CentOS 5.4 Resin Web

64 JDK 1.5 -Xmx -Xms Java 12GB

GC Server
12GB Full GC 14

Minor GC
12GB

32 1.5GB

Java

64 JDK

32

Java Full GC
Full GC
Full GC

Full GC “ ”

Full GC
64 JDK
64 JDK 32 JDK

GB Dump

64 JDK 32 JDK

32

64 JDK

Session
SessionID

IO

JNDI

32 32 Windows
2GB 1.5GB Linux UNIX
Solaris 3GB 4GB 32
4GB 2 32

HashMap K/V

5 32
JDK 2GB 1.5GB 10GB
Apache
CPU CMS
5.2.2
B/S MIS 2 CPU 8GB HP
WebLogic 9.2 3 WebLogic 6
Session

JBossCache

-XX
+HeapDumpOnOutOfMemoryError
heapdump org.jgroups.protocols.pbcast.NAKACK

JBossCache JGroups JGroups


up
down NAKACK JBossCache
5-1

5-1 JBossCache

GMS Group Membership


Service MIS
Filter
JBossCache MIS
JBossCache maillist
JBossCache
5.2.3
B/S
AJAX Comet Server Side Push
CometD 1.1.1 Jetty 7.1.4 PC Core i5
CPU 4GB 32 Windows

32 1.6GB
-XX +HeapDumpOnOutOfMemoryError
jstat GC
Eden Survivor “ ”

5-1

5-1

[org.eclipse.jetty.util.log]handle failed java.lang.OutOfMemoryError null


at sun.misc.Unsafe.allocateMemory Native Method
at java.nio.DirectByteBuffer. init DirectByteBuffer.java 99
at java.nio.ByteBuffer.allocateDirect ByteBuffer.java 288
at org.eclipse.jetty.io.nio.DirectNIOBuffer. init
……

2
32
Windows 2GB 1.6GB Java Direct Memory 1.6GB
0.4GB
Direct Memory Direct Memory

Full GC “ ”
catch catch “ ” “System.gc ”
-XX +DisableExplicitGC
CometD 1.1.1
NIO Direct Memory

Java

Direct Memory -XX MaxDirectMemorySize


OutOfMemoryError OutOfMemoryError Direct buffer memory

-Xss StackOverflowError
OutOfMemoryError unable to create new native thread

Socket Socket Receive Send 37KB 25KB


IOException Too
many open files

JNI JNI

GC GC
5.2.4
4 CPU Solaris 10
GlassFish
mpstat CPU CPU
CPU

Solaris 10 Dtrace CPU


Dtrace CPU “fork” “fork”
Linux Java Java

shell shell Java


Runtime.getRuntime .exec Java

Java

CPU

Shell Java API


5.2.5 JVM
B/S MIS 2 CPU 8GB HP
WebLogic 9.2 5.2.2
hs_err_pid###.log

5-2

5-2 2

java.net.SocketException Connection reset


at java.net.SocketInputStream.read SocketInputStream.java 168
at java.io.BufferedInputStream.fill BufferedInputStream.java 218
at java.io.BufferedInputStream.read BufferedInputStream.java 235
at org.apache.axis.transport.http.HTTPSender.readHeadersFromSocket HTTPSender.java 583
at org.apache.axis.transport.http.HTTPSender.invoke HTTPSender.java 143 ……99 more

OA
MIS Web OA
OA SoapUI Web
3

MIS OA
Web Web
Socket
OA
/
5.2.6
RPC 64 -Xms4g-Xmx8g-Xmn1g
ParNew+CMS Minor GC 30
10 80MB
100 HashMap Long,Long Entry Minor GC
500 GC

{Heap before GC invocations=95 full 4


par new generation total 903168K,used 803142K[0x00002aaaae770000 0x00002aaaebb70000 0x00002aaaebb70000
eden space 802816K 100%used[0x00002aaaae770000 0x00002aaadf770000 0x00002aaadf770000
from space 100352K 0%used[0x00002aaae5970000 0x00002aaae59c1910 0x00002aaaebb70000
to space 100352K 0%used[0x00002aaadf770000 0x00002aaadf770000 0x00002aaae5970000
concurrent mark-sweep generation total 5845540K,used 3898978K[0x00002aaaebb70000 0x00002aac507f9000 0x00002aacae770000
concurrent-mark-sweep perm gen total 65536K,used 40333K[0x00002aacae770000 0x00002aacb2770000 0x00002aacb2770000
2 0 1 1-1 0-2 8 T 1 1 4 0 4 5.1 6 2+0 8 0 0 2 2 6.5 0 4 [G C 2 2 6.5 0 4 [P a r N e w 803142K- 100352K 903168K 0.5995670 secs]4702120K-
4056332K 6748708K 0.5997560
secs][Times user=1.46 sys=0.04 real=0.60 secs]
Heap after GC invocations=96 full 4
par new generation total 903168K,used 100352K[0x00002aaaae770000 0x00002aaaebb70000 0x00002aaaebb70000
eden space 802816K 0%used[0x00002aaaae770000 0x00002aaaae770000 0x00002aaadf770000
from space 100352K 100%used[0x00002aaadf770000 0x00002aaae5970000
0x00002aaae5970000
to space 100352K 0x00002aaaebb70000 0%used[0x00002aaae5970000 0x00002aaae5970000
concurrent mark-sweep generation total 5845540K,used 3955980K[0x00002aaaebb70000 0x00002aac507f9000 0x00002aacae770000
concurrent-mark-sweep perm gen total 65536K,used 40333K[0x00002aacae770000 0x00002aacb2770000 0x00002aacb2770000
}
Total time for which application threads were stopped 0.6070570 seconds

Minor GC
Minor GC Eden Survivor
800MB Eden GC Minor GC
ParNew
“ ” Survivor
GC

GC Survivor
-XX SurvivorRatio=65536 -XX MaxTenuringThreshold=0 -XX
+AlwaysTenure Minor GC Major
GC
HashMap Long,Long

HashMap Long,Long Key Value


16B 2×8B java.lang.Long
8B MarkWord 8B Klass 8B long
Long Map.Entry 16B 8B next 4B int
hash 4B HashMap Entry 8B

Long 24B ×2 +Entry 32B +HashMap Ref 8B =88B 16B/88B=18%


5.2.7 Windows [1]

GUI 15
30

-Xmx256m GC
-XX +PrintGCApplicationStoppedTime-XX +PrintGCDateStamps-
Xloggc gclog.log GC GC GC
100 1 GC

Total time for which application threads were stopped 0.0112389 seconds
Total time for which application threads were stopped 0.0001335 seconds
Total time for which application threads were stopped 0.0003246 seconds
Total time for which application threads were stopped 41.4731411 seconds
Total time for which application threads were stopped 0.0489481 seconds
Total time for which application threads were stopped 0.1110761 seconds
Total time for which application threads were stopped 0.0007286 seconds
Total time for which application threads were stopped 0.0001268 seconds

GC -XX +PrintReferenceGC
GC
GC GC

2012-08-29T19 14 30.968+0800 10069.800 [GC10099.225 [SoftReference 0 refs 0.0000109 secs]10099.226 [WeakReference 4072 refs 0.0012099
secs]10099.227 [FinalReference 984 refs 1.5822450 secs]10100.809 [PhantomReference 251 refs 0.0001394 secs]10100.809 [JNI Weak Reference 0.0994015 secs]
[PSYoungGen 175672K- 8528K 167360K ]251523K- 100182K 353152K 31.1580402 secs][Times user=0.61 sys=0.52 real=31.16 secs]

GC GUI

GC
GC

MSDN [2]
Java GUI
“-Dsun.awt.keepWorkingSetOnMinimize=true” AWT
JDK Visual VM

[1] HLLVM http://hllvm.group.iteye.com/group/topic/28745


[2]http://support.microsoft.com/default.aspx?scid=kb en-us 293215
5.3 Eclipse
Java
5.2

Java

5.3.1
Eclipse IDE
Klocwork ClearCase LT Eclipse
Eclipse “

Eclipse 32 Windows 7 HotSpot VM 1.5 b64


ThinkPad X201 Intel i5 CPU 4GB eclipse.ini
JDK 512MB JMX VisualVM
5-3

5-3 Eclipse 3.5

-vm
D /_DevSpace/jdk1.5.0/bin/javaw.exe
-startup
plugins/org.eclipse.equinox.launcher_1.0.201.R35x_v20090715.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.0.200.v20090519
-product
org.eclipse.epp.package.jee.product
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xmx512m
-Dcom.sun.management.jmxremote

Eclipse
VisualVM VisualGC
Eclipse
5-2
5-2 Eclipse

Eclipse VisualVM Eclipse


Eclipse
Eclipse Eclipse RCP
5-4

5-4 Eclipse

ShowTime.java
import org.eclipse.jface.dialogs.MessageDialog
import org.eclipse.swt.widgets.Display
import org.eclipse.swt.widgets.Shell
import org.eclipse.ui.IStartup
/**
* Eclipse
*@author zzm
*/
public class ShowTime implements IStartup{
public void earlyStartup {
Display.getDefault .syncExec new Runnable {
public void run {
long eclipseStartTime=Long.parseLong System.getProperty "eclipse.startTime"
long costTime=System.currentTimeMillis -eclipseStartTime
Shell shell=Display.getDefault .getActiveShell
String message="Eclipse "+costTime+"ms"
MessageDialog.openInformation shell "Information" message
}
}
}
}
plugin.xml
?xml version="1.0"encoding="UTF-8"?
?eclipse version="3.4"?
plugin
extension
point="org.eclipse.ui.startup"
startup class="eclipsestarttime.actions.ShowTime"/
/extension
/plugin
jar Eclipse plugins
15 5-3

5-3

VisualGC Eclipse

15

4.149

●Full GC 19 3.166

●Minor GC 378 0.983

9115 4.114

JIT 1.999

512MB 40MB 31.5 Eden 4MB Surviver


472MB

2010 PC 15
VisualGC
5-2 Compile Time Class Load Time GC Time
JIT

Eclipse
5.3.2 JDK 1.6
Eclipse
“ ”

JDK

[1]
JDK 1.5 1.6 1.7 4
[2]

500

500 ArrayList String

500 HashMap String,Integer -

500 ArrayList String

JDK 3 5-4
5-4 JDK

4 JDK 1.6 JDK 1.5 15% JDK


4 JDK
SPECjvm2008 [3]

TCK [4]

“ ” JDK 1.6 Update 21

JDK 1.6
Eclipse “ ” 5-5
5-5 Eclipse OutOfMemoryError

Eclipse
eclipse.ini JVM
Eclipse
JDK 1.6 Update 21 API

JDK 1.6
VisualVM
5-6 5-7
5-6 Java
5-7

Java “ ” “ ”
“ ” “
” “ ”
-Xms -Xmx
“ ”
Java
“PermGen ” “
PermGen” “
PermGen” “PermGen ”

5-7 “67 108 864 ” 64MB


JDK -XX MaxPermSize JDK 1.5
JDK 1.6 64MB Eclipse Java 64MB
JDK 1.5

VisualVM “ -JVM ” JDK 1.5 JDK 1.6 Eclipse


JVM JDK 1.6 3 JVM 5-5

5-5 JDK 1.6 Eclipse


-Dcom.sun.management.jmxremote
-Dosgi.requiredJavaVersion=1.5
-Xmx512m

JDK 1.5 4 JVM


-XX MaxPermSize=256M 5-6

5-6 JDK 1.5 Eclipse

-Dcom.sun.management.jmxremote
-Dosgi.requiredJavaVersion=1.5
-Xmx512m
-XX MaxPermSize=256M

Eclipse Bug List [5]


JDK 1.5
eclipse.ini “--launcher.XXMaxPermSize 256M”
launcher—— Windows eclipse.exe Eclipse
Sun -XX MaxPermSize
Sun HotSpot
JRockit IBM J9

2009 4 20
Oracle Sun
Sun Oracle eclipse.exe Sun
JDK 1.6 Update 21 java.exe javaw.exe “Company” “Sun Microsystems
Inc.” “Oracle Corporation” Eclipse

launcher
eclipse.ini -XX MaxPermSize=256M

[1]
JDK
[2] http://geeknizer.com/java-7-whats-new-performance-benchmark-
1-5-1-6-1-7
[3] http://www.spec.org/jvm2008/docs/UserGuide.html
[4]TCK Technology Compatibility Kit
Java Java

[5]https://bugs.eclipse.org/bugs/show_bug.cgi?id=319514
5.3.3
Eclipse JDK 1.6 ……
JDK 1.5

Sun JDK 1.6 [1]


JDK 1.5

JDK 1.6 Eclipse JDK 1.5


JDK 1.6 JDK 1.5 5-7

5-7 JDK 1.5 JDK 1.6

JDK 1.6
C \Users\IcyFenix jps
3552
6372 org.eclipse.equinox.launcher_1.0.201.R35x_v20090715.jar
6900 Jps
C \Users\IcyFenix jstat-class 6372
Loaded Bytes Unloaded Bytes Time
7917 10190.3 0 0.0 8.18
JDK 1.5
C \Users\IcyFenix jps
3552
7272 Jps
7216 org.eclipse.equinox.launcher_1.0.201.R35x_v20090715.jar
C \Users\IcyFenix jstat-class 7216
Loaded Bytes Unloaded Bytes Time
7902 9691.2 3 2.6 4.34

JDK 1.6
JDK 1.5 Tomcat GlassFish
Java [2]

JDK 1.6 Update

JDK
Eclipse
-Xverify none
JDK JDK 1.6
JDK 1.5 5-8

5-8 JDK 1.5 JDK 1.6

JDK 1.6
C \Users\IcyFenix jps
5512 org.eclipse.equinox.launcher_1.0.201.R35x_v20090715.jar
5596 Jps
C \Users\IcyFenix jstat-class 5512
Loaded Bytes Unloaded Bytes Time
6749 8837.0 0 0.0 3.94
JDK 1.5
C \Users\IcyFenix jps
4724 org.eclipse.equinox.launcher_1.0.201.R35x_v20090715.jar
5412 Jps
C \Users\IcyFenix jstat-class 4724
Loaded Bytes Unloaded Bytes Time
6885 9109.7 3 2.6 3.10

JDK 1.5 13 JDK 1.6


JDK 1.5 1 12 5-8
JDK 1.6 JDK 1.5 Eclipse
JDK “ ”

5-8 JDK 1.6

VisualGC
Compile Time GC Time
JIT

JIT Just In Time Compiler Hot Spot Code


Java Java Class
ByteCode C/C++
JDK 1.2
[3]
Java
JIT HotSpot
C/C++

Java
Java

“ ”

-Xint
Eclipse 2 “ ”
0 Eclipse
27 JDK 1.2

-client
C1 C2
-server Eclipse C2
VisualGC 15
Eclipse C2
-server
-client Eclipse
[1]http://www.oracle.com/technetwork/java/6-performance-137236.html
[2] JDK 1.6 JDK 1.5 Eclipse
http://www.iteye.com/topic/826542
[3]JDK 1.2 JIT
5.3.4
GC GC

Eclipse 15 19 Full GC 378 Minor


GC 397 GC 4 1/4

Minor GC GC 1 378
VisualGC Eclipse 70
25 [1]

SafePoint GC

GC Eden
Survivor 35MB -Xmn

19 Full GC 19 “ ” 378 Minor GC


3.166 GC GC
VisualGC GC [2]
Full GC
5-9 2.5 10 Full GC

5-9 Full GC

0.278 [GC 0.278 [DefNew 574K- 33K 576K 0.0012562 secs]0.279 [Tenured 1467K- 997K 1536K 0.0181775 secs]1920K- 997K 2112K 0.0195257 secs]
0.312 [GC 0.312 [DefNew 575K- 64K 576K 0.0004974 secs]0.312 [Tenured 1544K- 1608K 1664K 0.0191592 secs]1980K- 1608K 2240K 0.0197396 secs]
0.590 [GC 0.590 [DefNew 576K- 64K 576K 0.0006360 secs]0.590 [Tenured 2675K- 2219K 2684K 0.0256020 secs]3090K- 2219K 3260K 0.0263501 secs]
0.958 [GC 0.958 [DefNew 551K- 64K 576K 0.0011433 secs]0.959 [Tenured 3979K- 3470K 4084K 0.0419335 secs]4222K- 3470K 4660K 0.0431992 secs]
1.575 [Full GC 1.575 [Tenured 4800K- 5046K 5784K 0.0543136 secs]5189K- 5046K 6360K [Perm 12287K- 12287K 12288K ] 0.0544163 secs]
1.703 [GC 1.703 [DefNew 703K- 63K 704K 0.0012609 secs]1.705 [Tenured 8441K- 8505K 8540K 0.0607638 secs]8691K- 8505K 9244K 0.0621470 secs]
1.837 [GC 1.837 [DefNew 1151K- 64K 1152K 0.0020698 secs]1.839 [Tenured 14616K- 14680K 14688K 0.0708748 secs]15035K- 14680K 15840K 0.0730947
secs]
2.144 [GC 2.144 [DefNew 1856K- 191K 1856K 0.0026810 secs]2.147 [Tenured 25092K- 24656K 25108K 0.1112429 secs]26172K-
24656K 26964K 0.1141099 secs]
2.337 [GC 2.337 [DefNew 1914K- 0K 3136K 0.0009697 secs]2.338 [Tenured 41779K- 27347K 42056K 0.0954341 secs]42733K- 27347K 45192K 0.0965513
secs]
2.465 [GC 2.465 [DefNew 2490K- 0K 3456K 0.0011044 secs]2.466 [Tenured 46379K- 27635K 46828K 0.0956937 secs]47621K- 27635K 50284K 0.0969918
secs]

GC 10 Full GC
Full GC 1536KB-
1664KB- 2684KB……42056KB- 46828KB 10 GC 1536KB
46828KB 15 Eclipse 103428KB
473MB Java 512MB

“Tenured 25092K- 24656K 25108K 0.1112429 secs”


25108KB 25092KB Full GC 0.11
24656KB 500KB GC
0.11

Eclipse Full GC

-Xms -XX PermSize -Xmx -XX MaxPermSize


[3]

128MB GC Java
512MB 96MB [4]

Eclipse VisualGC
eclipse.ini 5-10

5-10 Eclipse

-vm
D /_DevSpace/jdk1.6.0_21/bin/javaw.exe
-startup
plugins/org.eclipse.equinox.launcher_1.0.201.R35x_v20090715.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.0.200.v20090519
-product
org.eclipse.epp.package.jee.product
-showsplash
org.eclipse.platform
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xverify none
-Xmx512m
-Xms512m
-Xmn128m
-XX PermSize=96m
-XX MaxPermSize=96m

GC 5-9 Eclipse 1
8 Minor GC 4 Full GC 1.928
5-9 GC

Old Gen
384MB 66MB Full GC
4 Full GC jstat-gccause GC 5-
11

5-11 GC

C \Users\IcyFenix jps
9772 Jps
4068 org.eclipse.equinox.launcher_1.0.201.R35x_v20090715.jar
C \Users\IcyFenix jstat-gccause 4068
S0 S1 E O P YGC YGCT FGC FGCT GCT LGCC GCC
0.00 0.00 1.00 14.81 39.29 6 0.422 20 5.992 6.414
System.gc No GC

LGCC Last GC Cause System.gc GC


GC eclipse.ini -XX
+DisableExplicitGC System.gc Full GC
6 Minor GC 417 4.149
GC Eclipse GC
7 5-10
5-10 Eclipse
[1] native native Java

[2] GC -XX +PrintGCTimeStamps GC


-XX +PrintGCDetails GC -verbose gc GC
-Xloggc gc.log
[3]

“Virtual”
[4]512MB 96MB
VMWare
5.3.5
Eclipse Eclipse
Eclipse
5-11 Eclipse
65 725
GC 65 GC 1

5-11

CPU 5-12 Eclipse CPU


30% CPU CPU
CPU
5-12 CPU

GC CPU Client

Eclipse
“Run in Backgroup”
3 CMS
eclipse.ini -XX +UseConcMarkSweepGC -XX
+UseParNewGC ParNew CMS
ParNew CMS
5-13
65 53 725
36
5-13 ParNew CMS GC

CMS 725
36 GC CMS 400

I/O

eclipse.ini 5-12

5-12 Eclipse

-vm
D /_DevSpace/jdk1.6.0_21/bin/javaw.exe
-startup
plugins/org.eclipse.equinox.launcher_1.0.201.R35x_v20090715.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.0.200.v20090519
-product
org.eclipse.epp.package.jee.product
-showsplash
org.eclipse.platform
-vmargs
-Dcom.sun.management.jmxremote
-Dosgi.requiredJavaVersion=1.5
-Xverify none
-Xmx512m
-Xms512m
-Xmn128m
-XX PermSize=96m
-XX MaxPermSize=96m
-XX +DisableExplicitGC
-Xnoclassgc
-XX +UseParNewGC
-XX +UseConcMarkSweepGC
-XX CMSInitiatingOccupancyFraction=85
5.4
Java
2 5

Class
6

9
6

6.1
“ 0 1
0 1 ” 10
0 1 10
Native
Code
6.2
CPU x86 Windows Java
Java “
Write Once,Run Anywhere ”
IT Wintel [1]
Wintel
“ ”
Sun

“ ”

—— ByteCode
“ ”
——
Java Java Java
Java
Java Java The Java Language
Specification Java The Java Virtual Machine Specification 1997
Java “In the future,we will consider bounded extensions
to the Java virtual machine to provide better support for other languages” Java
JVM Java
JDK 1.7 1.8 JVM JSR-292

Java Java
Clojure Groovy JRuby Jython Scala
Java

Java Java
“Class ” Class
Java Java
Class
Java Class
Java Java
Java Class JRuby
Class Class 6-1
6-1 Java

Java
Java
Java
Java

[1]Wintel Windows Intel


6.3 Class
Class

Class Java 2 1999


JDK 1.4 Java
Class JDK 1.5 JDK 1.7

Java Java SE 7
http://icyfenix.iteye.com/ PDF

Class

“Class ”

Class 8
Class Class
8
[1]
8

Java Class C

u1 u2 u4 u8 1 2 4
8 UTF-8

“_info” Class
6-1
Class XML
6-1
Byte Ordering,Class Big-Endian

6.3.1 Class
Class 4 Magic Number
Class
gif jpeg

Class
“ ” 0xCAFEBABE Java
“Oak” 1991
Java Patrick Naughton “
0xCAFEBABE Peet’s Coffee
Baristas ” “Java”

4 Class 5 6 Minor
Version 7 8 Major Version Java 45
JDK 1.1 JDK 1 JDK 1.0 1.1 45.0 45.3
JDK Class Class
Class

JDK 1.1 45.0 45.65535 Class 46.0


Class JDK 1.2 45.0 46.65535 Class JDK
1.7 Class 51.0

Java 6-1
JDK 1.6 Class

6-1 Java

package org.fenixsoft.clazz
public class TestClass{
private int m
public int inc {
return m+1
}
}

6-2 WinHex Class


4 0xCAFEBABE 5 6
0x0000 0x0032 50
JDK 1.6 Class

6-2 Java Class

6-2 JDK 1.1 JDK 1.7 JDK Class


[1] “Big-Endian”
SPARC PowerPC x86
“Little-Endian”
6.3.2
Class
Class Class
Class

u2
constant_pool_count Java
1 0 6-3 0x00000008
0x0016 22 21 1 21
Class 0

” 0 Class
1
0

6-3

Literal Symbolic References


Java final

Fully Qualified Name

Descriptor

Java Javac C C++ “ ”


Class Class

JDK 1.7 11
JDK 1.7 3
CONSTANT_MethodHandle_info CONSTANT_MethodType_info
CONSTANT_InvokeDynamic_info 3 8
14 u1 tag
6-3 14
6-3

14
6-3 0x0000000A 0x07 6-3
CONSTANT_Class_info
CONSTANT_Class_info 6-4

tag name_index
CONSTANT_Utf8_info
name_index 0x0000000B 0x0002
6-3 0x0000000D 0x01
6-3 CONSTANT_Utf8_info CONSTANT_Utf8_info
6-5

length UTF-8 length


UTF-8 UTF-8 UTF-8
'\u0001' '\u007f' 1 127 ASCII
'\u0080' '\u07ff'
'\u0800' '\uffff' UTF-8

Class CONSTANT_Utf8_info
CONSTANT_Utf8_info Java
length u2 65535 Java
64KB

length 0x0000000E 0x001D 29


29 1 127 ASCII “org/fenixsoft/clazz/TestClass”
6-4

6-4 UTF-8

TestClass.class 21 19
19
JDK bin Oracle
Class javap 6-2 javap -verbose
TestClass.class
Class 6-2

6-2 Javap

C \ javap-verbose TestClass
Compiled from"TestClass.java"
public class org.fenixsoft.clazz.TestClass extends java.lang.Object
SourceFile "TestClass.java"
minor version 0
major version 50
Constant pool
const#1=class#2 //org/fenixsoft/clazz/TestClass
const#2=Asciz org/fenixsoft/clazz/TestClass
const#3=class#4 //java/lang/Object
const#4=Asciz java/lang/Object
const#5=Asciz m
const#6=Asciz I
const#7=Asciz init
const#8=Asciz V
const#9=Asciz Code
const#10=Method#3.#11 //java/lang/Object." init " V
const#11=NameAndType#7 #8 //" init " V
const#12=Asciz LineNumberTable
const#13=Asciz LocalVariableTable
const#14=Asciz this
const#15=Asciz Lorg/fenixsoft/clazz/TestClass
const#16=Asciz inc
const#17=Asciz I
const#18=Field#1.#19 //org/fenixsoft/clazz/TestClass.m I
const#19=NameAndType#5 #6 //m I
const#20=Asciz SourceFile
const#21=Asciz TestClass.java

6-2 21
1 2
“I” “V” “ init ” “LineNumberTable”
“LocalVariableTable”

Java
field_info method_info attribute_info
“ ”
Java “ ”

14
6-6
6.3.3
access_flags
Class public
abstract final
6-7

access_flags 16 8 [1]

0 6-1 TestClass Java


public final abstract JDK 1.2
ACC_PUBLIC ACC_SUPER ACC_FINAL
ACC_INTERFACE ACC_ABSTRACT ACC_SYNTHETIC ACC_ANNOTATION
ACC_ENUM 6 access_flags 0x0001|0x0020=0x0021
6-5 access_flags 0x000000EF 0x0021

6-5 access_flags
[1] Java 5 JDK 1.5 3
JSR-202 Java 2
JSR-202
6.3.4
this_class super_class u2
interfaces u2 Class

Java java.lang.Object Java


java.lang.Object Java 0
implements
extends

u2 CONSTANT_Class_info
CONSTANT_Class_info
CONSTANT_Utf8_info 6-6 6-1

——u2
interfaces_count 0
6-1
6-7

6-6

6-7

0x000000F1 3 u2 0x0001 0x0003 0x0000


1 3 0 6-2 javap
6-3

6-3

const#1=class#2 //org/fenixsoft/clazz/TestClass
const#2=Asciz org/fenixsoft/clazz/TestClass
const#3=class#4 //java/lang/Object
const#4=Asciz java/lang/Object
6.3.5
field_info field
Java
public private protected
static final volatile
transient

6-8

access_flags access_flags
u2 6-9

ACC_PUBLIC ACC_PRIVATE ACC_PROTECTED


ACC_FINAL ACC_VOLATILE
ACC_PUBLIC ACC_STATIC ACC_FINAL Java

access_flags name_index descriptor_index



” “ ” “ ”

6-1
“org/fenixsoft/clazz/TestClass” “.”
“/”
“ ”
inc m “inc” “m”

byte char double float int long short boolean


void L
6-10

[1]

“[”
“java.lang.String[][]” “[[Ljava/lang/String ”
“int[]” “[I”

“ ” void inc “ V”
java.lang.String toString “ Ljava/lang/String ” int
indexOf char[]source,int sourceOffset,int sourceCount,char[]target,int targetOffset,int
targetCount,int fromIndex “ [CII[CIII I”

6-1 TestClass.class 0x000000F8


u2 fields_count 6-8 0x0001
access_flags 0x0002 private
ACC_PRIVATE ACC_PRIVATE 0x0002
name_index 0x0005 6-2 5
CONSTANT_Utf8_info “m”
descriptor_index 0x0006 “I”
“private int m ”
descriptor_index descriptor_index

m 0
m “final static int m=123 ”
ConstantValue 123 attribute_info 6.3.7

6-8

Java

Java

[1]void “VoidDescriptor”
6.3.6
Class

access_flags name_index
descriptor_index attributes 6-11

volatile transient
ACC_VOLATILE ACC_TRANSIENT synchronized native strictfp
abstract ACC_SYNCHRONIZED
ACC_NATIVE ACC_STRICTFP ACC_ABSTRACT
6-12

Java
“Code” Class
6.3.7

6-1 Class 6-9


0x00000101 u2
0x0002 init
inc 0x001 ACC_PUBLIC
0x0007 6-2 “ init ”
0x0008 “ V” attributes_count 0x0001
0x0009 “Code”

6-9

Override

“ clinit ” “ init ” [1]

Java Overload
[2]

Java
Class

Class

[1] init clinit 10


[2] Java 2 “§4.4.4 Signatures” Java 3
“§8.4.2 Method Signature” Java
Java
6.3.7
attribute_info Class

Class

Java
Class Java 2 9
Java Java SE 7
21 6-13
CONSTANT_Utf8_info
u4
6-14

1.Code

Java Javac Code


Code
Code Code
6-15

attribute_name_index CONSTANT_Utf8_info
“Code” attribute_length
6 6

max_stack Operand Stacks


Stack
Frame

max_locals max_locals Slot,Slot


byte char float int short boolean
returnAddress 32 1 Slot double long
64 Slot
“this” Exception Handler Parameter try-catch catch

Slot max_locals
Slot
Slot Javac Slot
max_locals

code_length code Java code_length


code
u1 code

u1 0x00 0xFF 0 255


256 Java 200
B“ ”

code_length u4
2 -1
32
65535
u2 Javac
Java
JSP JSP
JSP

Code Class Java


Code Java Metadata
Class Code
Code
Java

6-1 TestClass.class 6-10


“ init ” Code
0x0001 0x0005
5 “2A B7
00 0A B1”

1 2A 0x2A aload_0 0 Slot


reference

2 B7 0xB7 invokespecial
reference private
u2
CONSTANT_Methodref_info
3 00 0A invokespecial 0x000A
“ init ”

4 B1 0xB1 return void

6-10 Code

Java
invokespecial

javap Class
6-4

6-4 javap

// Java
public class TestClass{
private int m
public int inc {
return m+1
}
}
C \ javap-verbose TestClass
// 6-1
{
public org.fenixsoft.clazz.TestClass
Code
Stack=1 Locals=1 Args_size=1
0 aload_0
1 invokespecial#10 //Method java/lang/Object." init " V
4 return
LineNumberTable
line 3 0
LocalVariableTable
Start Length Slot Name Signature
0 5 0 this Lorg/fenixsoft/clazz/TestClass
public int inc
Code
Stack=2 Locals=1 Args_size=1
0 aload_0
1 getfield#18 //Field m I
4 iconst_1
5 iadd
6 ireturn
LineNumberTable
line 8 0
LocalVariableTable
Start Length Slot Name Signature
0 7 0 this Lorg/fenixsoft/clazz/TestClass
}

javap “Args_size” ——
init inc Args_size
1 Locals
1
“this” Java
Javac this
Slot 1
6-1 inc static Args_size 1 0

Code 6-4

4 6-16
start_pc end_pc
[1]
end_pc catch_type
catch_type CONSTANT_Class_info handler_pc
catch_type 0 handler_pc

Java
Java finally [2]

6-5
try-catch-finally Java

6-5

//Java
public int inc {
int x
try{
x=1
return x
}catch Exception e {
x=2
return x
}finally{
x=3
}
}
// ByteCode
public int inc
Code
Stack=1 Locals=5 Args_size=1
0 iconst_1//try x=1
1 istore_1
2 iload_1// x returnValue x=1
3 istore 4
5 iconst_3//finaly x=3
6 istore_1
7 iload 4// returnValue ireturn
9 ireturn
10 astore_2// catch Exception e Slot 2
11 iconst_2//catch x=2
12 istore_1
13 iload_1// x returnValue x=2
14 istore 4
16 iconst_3//finaly x=3
17 istore_1
18 iload 4// returnValue ireturn
20 ireturn
21 astore_3// java.lang.Exception
22 iconst_3//finaly x=3
23 istore_1
24 aload_3//
25 athrow
Exception table
from to target type
0 5 10 Class java/lang/Exception
0 5 21 any
10 16 21 any
Java 3 3
Java 3

try Exception catch

try Exception finally

catch finally

Java
1 Exception
2 Exception

0 4 1 x x
Slot Slot ireturn
Slot returnValue
5 9 x 3
returnValue 1 ireturn int
PC 10 10 20 2
x x returnValue x 3
returnValue 2 21 x
3

2.Exceptions

Exceptions Code
Exceptions
Checked Excepitons throws
6-17

Exceptions number_of_exceptions number_of_exceptions


exception_index_table exception_index_table
CONSTANT_Class_info
3.LineNumberTable

LineNumberTable Java
Class Javac
-g none -g lines LineNumberTable

LineNumberTable 6-
18

line_number_table line_number_table_length line_number_info


line_number_info start_pc line_number u2
Java

4.LocalVariableTable

LocalVariableTable Java
Class Javac
-g none -g vars
IDE arg0
arg1
LocalVariableTable
6-19

local_variable_info 6-
20
start_pc length

name_index descriptor_index CONSTANT_Utf8_info

index Slot 64
double long Slot index index+1

JDK 1.5 LocalVariableTable “ ”


LocalVariableTypeTable LocalVariableTable
descriptor_index Signature
[3]

LocalVariableTypeTable

5.SourceFile

SourceFile Class
Javac -g none -g source Java

6-21

sourcefile_index CONSTANT_Utf8_info
6.ConstantValue

ConstantValue static
“int x=123” “static int x=123”
Java
static init
clinit ConstantValue
Sun Javac final static
“ ” java.lang.String
ConstantValue final
clinit

final “ConstantValue”
ACC_FINAL ConstantValue ACC_STATIC
final Javac ConstantValue
String
Class
ConstantValue ConstantValue
6-22

ConstantValue attribute_length
2 constantvalue_index
CONSTANT_Long_info CONSTANT_Float_info
CONSTANT_Double_info CONSTANT_Integer_info CONSTANT_String_info

7.InnerClasses

InnerClasses
InnerClasses 6-23
number_of_classes
inner_classes_info inner_classes_info 6-24

inner_class_info_index outer_class_info_index CONSTANT_Class_info

inner_name_index CONSTANT_Utf8_info
0

inner_class_access_flags access_flags
6-25
8.Deprecated Synthetic

Deprecated Synthetic

Deprecated
@deprecated

Synthetic Java
JDK 1.5
ACC_SYNTHETIC Bridge Method
Synthetic ACC_SYNTHETIC
“ init ” “ clinit ”

Deprecated Synthetic 6-26

attribute_length 0x00000000

9.StackMapTable

StackMapTable JDK 1.6 Class


Code
Type Checker 7.3.2

Sheng Liang
Java ME CLDC Class

Verification Types Class


JDK 1.6
JDK 1.7
Java Java SE 7 120

StackMapTable Stack Map Frames

StackMapTable 6-27

Java Java
SE 7 50.0 Class
Code StackMapTable
StackMap StackMap number_of_entries 0 StackMapTable
Code StackMapTable ClassFormatError

10.Signature

Signature JDK 1.5 Class


JDK 1.5 Java
Type
Variables Parameterized Types Signature
Java
Code
Javac
Backport
C#
Signature
Java API Java
Signature 10
Signature 6-28

signature_index
CONSTANT_Utf8_info
Signature Signature
Signature

11.BootstrapMethods

BootstrapMethods JDK 1.7 Class


invokedynamic
Java Java SE 7
CONSTANT_InvokeDynamic_info
BootstrapMethods CONSTANT_InvokeDynamic_info
BootstrapMethods BootstrapMethods
JSR-292 InvokeDynamic java.lang.Invoke
InovkeDynamic 8 1

Javac InvokeDynamic BootstrapMethods


JSR-292
BootstrapMethods 6-29

bootstrap_method 6-30
BootstrapMethods num_bootstrap_methods bootstrap_methods[]
bootstrap_methods[]
CONSTANT_MethodHandle
bootstrap_methods[] 3

bootstrap_method_ref bootstrap_method_ref
CONSTANT_MethodHandle_info

num_bootstrap_arguments num_bootstrap_arguments bootstrap_arguments[]

bootstrap_arguments[] bootstrap_arguments[]
CONSTANT_String_info
CONSTANT_Class_info CONSTANT_Integer_info CONSTANT_Long_info
CONSTANT_Float_info CONSTANT_Double_info CONSTANT_MethodHandle_info
CONSTANT_MethodType_info

[1] “ ”
Java
[2] JDK1.4.2 Javac jsr ret finally 1.4.2
finally finally
JDK 1.7 Class jsr ret

[3] 10
6.4
Java
Opcode Operands
Java
8

Java
0 255 256
Class

16 byte1 byte2

byte1 8 |byte2

[1]

Java

Java

do{
PC 1
PC
if
}while 0

6.4.1
Java
iload int fload
float
Class

i int l long,s short,b byte,c


char,f float,d double,a reference
arraylength
goto

Java
Java
Java
Java “Not Orthogonal”

6-31 Java
opcode T

load int iload byte

6-31 byte char short


boolean byte short
Sign-Extend int boolean char Zero-
Extend int boolean byte short char
int boolean byte short
char int Computational
Type
Java
9
Java Java SE 7 6

[1] “tableswitch” “lookupswitch”


4
6.4.2
2

iload iload_ n lload lload_ n fload fload_


n dload dload_ n aload aload_ n

istore istore_ n lstore lstore_ n


fstore fstore_ n dstore dstore_ n astore astore_ n

bipush sipush ldc ldc_w ldc2_w aconst_null


iconst_m1 iconst_ i lconst_ l fconst_ f dconst_ d

wide

iload_ n
iload_ n iload_0 iload_1 iload_2
iload_3 iload

iload_0 0 iload
Java
6.4.3

Java byte
short char boolean int

iadd ladd fadd dadd

isub lsub fsub dsub

imul lmul fmul dmul

idiv ldiv fdiv ddiv

irem lrem frem drem

ineg lneg fneg dneg

ishl ishr iushr lshl lshr lushr

ior lor

iand land

ixor lxor

iinc

dcmpg dcmpl fcmpg fcmpl lcmp

Java Java
Java 3 4.2.2 4.2.4

Java
idiv ldiv
irem lrem ArithmeticException

Java IEEE 754


Java IEEE 754
Denormalized Floating-Point Numbers Gradual Underflow

Java
IEEE 754

Java IEEE 754

Java Java
IEEE 754 IEEE 754

NaN NaN
NaN

long
dcmpg dcmpl fcmpg fcmpl IEEE 754
Nonsignaling Comparisons
6.4.4

Java
Widening Numeric Conversions

int long float double

long float double

float double

Narrowing Numeric Conversions


i2b i2c i2s l2i f2i f2l d2i d2l d2f

int long T N
N T

T T int long

NaN int long 0

IEEE 754
v v T int long v

v T

double float IEEE 754 IEEE 754


float
float float
float float double NaN
float NaN

Java
6.4.5
Java
7

new

newarray anewarray multianewarray

static static
getfield putfield getstatic putstatic

baload caload saload iaload laload


faload daload aaload

bastore castore sastore iastore


fastore dastore aastore

arraylength

instanceof checkcast
6.4.6
Java

pop pop2

dup dup2
dup_x1 dup2_x1 dup_x2 dup2_x2

swap
6.4.7
Java

PC

ifeq iflt ifle ifne ifgt ifge ifnull ifnonnull if_icmpeq if_icmpne
if_icmplt if_icmpgt if_icmple if_icmpge if_acmpeq if_acmpne

tableswitch lookupswitch

goto goto_w jsr jsr_w ret

Java int reference


null null

boolean byte char short


int long float double
dcmpg dcmpl fcmpg
fcmpl lcmp 6.4.3 int
int
int Java int
6.4.8
8 5

invokevirtual
Java

invokeinterface

invokespecial

invokestatic static

invokedynamic
4 Java invokedynamic

ireturn boolean byte char short int lreturn freturn dreturn


areturn return void
6.4.9
Java throw athrow throw
Java Java

idiv ldiv ArithmeticException

Java catch
jsr ret
6.4.10
Java
Monitor

ACC_SYNCHRONIZED
ACC_SYNCHRONIZED

Java synchronized Java


monitorenter monitorexit synchronized
synchronized Javac Java 6-6

6-6

void onlyMe Foo f {


synchronized f {
doSomething
}
}

Method void onlyMe Foo


0 aload_1// f
1 dup// f
2 astore_2// Slot 2
3 monitorenter// f
4 aload_0// Slot 0 this
5 invokevirtual#5// doSomething
8 aload_2// Slow 2 f
9 monitorexit//
10 goto 18// 18
13 astore_3// Taget 13
14 aload_2// Slow 2 f
15 monitorexit//
16 aload_3// Slow 3
17 athrow// onlyMe
18 return//
Exception table
FromTo Target Type
4 10 13 any
13 16 13 any

monitorenter
monitorexit

6-6 monitorenter
monitorexit
monitorexit
6.5
Java Java Class
Java
Java

Java
Class Java Java

Class
Class
[1]

Java
Java

Java

Java CPU JIT

Java

[1] Debuggers Profilers


Just-In-Time Code Generator “ ”
6.6 Class
Class Java 1
Java JDK 1.0 1.7
API Java Class Class
[1]
Class

Java 2 Class
ACC_SYNTHETIC ACC_ANNOTATION
ACC_ENUM ACC_BRIDGE ACC_VARARGS 5 JDK 1.5
JDK 1.7 12 Java

JDK 1.6 StackMapTable Java


SourceDebugExtension

Class
Java

[1] JDK1.0.2
invokespecial JDK 1.7 invokedynamic ret jsr
6.7
Class Java Java
Class

Class
6-1 Java Class Class
7
7

7.1
Class Class
Class Class

Class
Java

Java

Java Java

Java

Java Applet JSP


OSGi Java

Class Java
“ ”
Class “Class
” “Class ”
7.2

Loading Verification Preparation Resolution


Initialization Using Unloading 7 3
Linking 7 7-1

7-1

7-1 5

Java
“ ” “ ” “ ”

Java

5 “ ”

1 new getstatic putstatic invokestatic 4


4 Java new
final

2 java.lang.reflect

4 main

5 JDK 1.7 java.lang.invoke.MethodHandle


REF_getStatic REF_putStatic REF_invokeStatic

5 “
” 5
3 7-1
7-3

7-1

package org.fenixsoft.classloading
/**
*
*
**/
public class SuperClass{
static{
System.out.println "SuperClass init "
}
public static int value=123
}
public class SubClass extends SuperClass{
static{
System.out.println "SubClass init "
}
}
/**
*
**/
public class NotInitialization{
public static void main String[]args {
System.out.println SubClass.value
}
}

“SuperClass init ” “SubClass init ”

Sun HotSpot
-XX +TraceClassLoading

7-2

package org.fenixsoft.classloading
/**
*
*
**/
public class NotInitialization{
public static void main String[]args {
SuperClass[]sca=new SuperClass[10]
}
}

7-1 SuperClass
“SuperClass init ” org.fenixsoft.classloading.SuperClass
“[Lorg.fenixsoft.classloading.SuperClass”

java.lang.Object newarray

org.fenixsoft.classloading.SuperClass
public length clone
Java C/C++
[1]
C/C++ Java
java.lang.ArrayIndexOutOfBoundsException
7-3

package org.fenixsoft.classloading
/**
*
*
**/
public class ConstClass{
static{
System.out.println "ConstClass init "
}
public static final String HELLOWORLD="hello world"
}
/**
*
**/
public class NotInitialization{
public static void main String[]args {
System.out.println ConstClass.HELLOWORLD
}
}

“ConstClass init ” Java


ConstClass HELLOWORLD
“hello world” NotInitialization NotInitialization
ConstClass.HELLOWORLD NotInitialization
NotInitialization Class ConstClass
Class

“static{}”
“static{}” “ clinit ”
[2]
5 “
” 3

[1] xaload
xastore
[2] clinit init 10
7.3
Java
5

7.3.1
“ ” “ ” Class Loading
3

3 java.lang.Class

3
“ ”
Class
“ ” Java
“ ” Java

ZIP JAR EAR WAR

Applet

java.lang.reflect.Proxy
ProxyGenerator.generateProxyClass “*$Proxy”

JSP JSP Class

SAP Netweaver

……

loadClass

Java
Element
Type
C

Component Type
C
7.4

int[] Java C

public

7.4

java.lang.Class Java
HotSpot Class
7.3.2
Class

Java C/C++ Java

Class
Java
Class Java

Java

Java 2
Class
Class java.lang.VerifyError
2011
Java Java SE 7 10
130
4

1.

Class

0xCAFEBABE

tag

CONSTANT_Utf8_info UTF8

Class

……

HotSpot [1]
Java

2.

Java

java.lang.Object

final

final

……

Java

3.

int long

……

“Halting Problem” [2]

——
JDK 1.6 Javac Java Code
“StackMapTable”
Basic Block
StackMapTable

StackMapTable
Code StackMapTable

JDK 1.6 HotSpot -XX -UseSplitVerifier


-XX +FailOverToOldVerifier
JDK 1.7 50 Class

4.

——

private protected public default

……

java.lang.IncompatibleClassChangeError
java.lang.IllegalAccessError java.lang.NoSuchFieldError java.lang.NoSuchMethodError

-Xverify none

[1] hotspot\src\share\vm\classfile\classFileParser.cpp
[2]

http://zh.wikipedia.org/zh/
7.3.3

static
Java “ ”

public static int value=123

value 0 123 Java


value 123 putstatic clinit
value 123 7-1 Java

“ ” “ ”
ConstantValue value
ConstantValue value

public static final int value=123

Javac value ConstantValue


ConstantValue value 123
7.3.4

Class Class CONSTANT_Class_info


CONSTANT_Fieldref_info CONSTANT_Methodref_info

Symbolic References

Java Class

Direct References

anewarray
checkcast getfield getstatic instanceof invokedynamic invokeinterface invokespecial
invokestatic invokevirtual ldc ldc_w multianewarray new putfield putstatic 16

invokedynamic

invokedynamic invokedynamic
invokedynamic
invokedynamic Java
“ ” Dynamic Call Site
Specifier “ ”
“ ”

7 CONSTANT_Class_info
CONSTANT_Fieldref_info CONSTANT_Methodref_info
CONSTANT_InterfaceMethodref_info CONSTANT_MethodType_info
CONSTANT_MethodHandle_info CONSTANT_InvokeDynamic_info 7 [1]

4 3 JDK 1.7
Java invokedynamic
Java 8

1.

D N
C 3

1 C N D
C

2 C N
“[Ljava/lang/Integer” 1 N
“java.lang.Integer”

3 C
D C
java.lang.IllegalAccessError

2.

class_index [2]

CONSTANT_Class_info

C
C

1 C

2 C

3 C java.lang.Object

4 java.lang.NoSuchFieldError

java.lang.IllegalAccessError
C
7-4 Sub “public static int A=4 ”
A “The field Sub.A is ambiguous”

7-4

package org.fenixsoft.classloading
public class FieldResolution{
interface Interface0{
int A=0
}
interface Interface1 extends Interface0{
int A=1
}
interface Interface2{
int A=2
}
static class Parent implements Interface1{
public static int A=3
}
static class Sub extends Parent implements Interface2{
public static int A=4
}
public static void main String[]args {
System.out.println Sub.A
}
}

3.

class_index [3]

1
class_index C java.lang.IncompatibleClassChangeError

2 1 C

3 C

4 C
C
java.lang.AbstractMethodError

5 java.lang.NoSuchMethodError

java.lang.IllegalAccessError

4.

class_index [4]

C
1 class_index C
java.lang.IncompatibleClassChangeError

2 C

3 C java.lang.Object
Object

4 java.lang.NoSuchMethodError

public
java.lang.IllegalAccessError

[1] CONSTANT_String_info CONSTANT_InterfaceMethodref_info

[2] 6 CONSTANT_Fieldref_info
[3] 6 CONSTANT_Methodref_info
[4] 6 CONSTANT_InterfaceMethodref_info
7.3.5

Java

clinit clinit
clinit
[1]

clinit
static{}

7-5

7-5

public class Test{


static{
i=0 //
System.out.print i // " "
}
static int i=1
}

clinit init
clinit
clinit clinit
java.lang.Object

clinit
7-6 B 2 1

7-6 clinit

static class Parent{


public static int A=1
static{
A=2
}
}
static class Sub extends Parent{
public static int B=A
}
public static void main String[]args {
System.out.println Sub.B
}

clinit
clinit

clinit clinit
clinit
clinit

clinit
clinit
clinit clinit
[2]

7-7

7-7

static class DeadLoopClass{


static{
/* if "Initializer does not complete normally" */
if true {
System.out.println Thread.currentThread +"init DeadLoopClass"
while true {
}
}
}
}
public static void main String[]args {
Runnable script=new Runnable {
public void run {
System.out.println Thread.currentThread +"start"
DeadLoopClass dlc=new DeadLoopClass
System.out.println Thread.currentThread +"run over"
}
}
Thread thread1=new Thread script
Thread thread2=new Thread script
thread1.start
thread2.start
}

Thread[Thread-0 5 main]start
Thread[Thread-1 5 main]start
Thread[Thread-0 5 main]init DeadLoopClass

[1] Java Class JVM


[2] clinit
clinit clinit
7.4

” Java
“ ”

Java Java
Java Applet Java Applet “ ” [1]

OSGi Java

7.4.1
Java
Java

“ ”
Class

“ ” Class equals isAssignableFrom


isInstance instanceof

7-8 instanceof

7-8 instanceof

/**
* instanceof
*
*@author zzm
*/
public class ClassLoaderTest{
public static void main String[]args throws Exception{
ClassLoader myLoader=new ClassLoader {
@Override
public Class ? loadClass String name throws ClassNotFoundException{
try{
String fileName=name.substring name.lastIndexOf "." +1 +".class"
InputStream is=getClass .getResourceAsStream fileName
if is==null {
return super.loadClass name
}
byte[]b=new byte[is.available ]
is.read b
return defineClass name,b 0 b.length
}catch IOException e {
throw new ClassNotFoundException name
}
}
}
Object obj=myLoader.loadClass "org.fenixsoft.classloading.ClassLoaderTest" .newInstance
System.out.println obj.getClass
System.out.println obj instanceof org.fenixsoft.classloading.ClassLoaderTest
}
}

class org.fenixsoft.classloading.ClassLoaderTest
false

7-8
Class
“org.fenixsoft.classloading.ClassLoaderTest”
org.fenixsoft.classloading.ClassLoaderTest
org.fenixsoft.classloading.ClassLoaderTest
false ClassLoaderTest

Class false

[1] Java Applets Java Applets


7.4.2
Java
Bootstrap ClassLoader C++ [1]

Java
java.lang.ClassLoader

Java Java
3

Bootstrap ClassLoader
JAVA_HOME \lib -Xbootclasspath
rt.jar lib
Java
null
7-9 java.lang.ClassLoader.getClassLoader

7-9 ClassLoader.getClassLoader

/**
Returns the class loader for the class.Some implementations may use null to represent the bootstrap class loader.This method will return null in such
implementations if this class was loaded by the bootstrap class loader.
*/
public ClassLoader getClassLoader {
ClassLoader cl=getClassLoader0
if cl==null
return null
SecurityManager sm=System.getSecurityManager
if sm =null {
ClassLoader ccl=ClassLoader.getCallerClassLoader
if ccl =null ccl =cl cl.isAncestor ccl {
sm.checkPermission SecurityConstants.GET_CLASSLOADER_PERMISSION
}
}
return cl
}

Extension ClassLoader sun.misc.Launcher


$ExtClassLoader JAVA_HOME \lib\ext java.ext.dirs

Application ClassLoader sun.misc.Launcher $App-


ClassLoader ClassLoader getSystemClassLoader
ClassPath

3
7-2
7-2

7-2 Parents
Delegation Model
Inheritance
Composition

JDK 1.2 Java


Java

Java
java.lang.Object
rt.jar
Object

java.lang.Object ClassPath Object


Java
rt.jar Java
[2]

Java
java.lang.ClassLoader loadClass 7-10
loadClass

ClassNotFoundException findClass

7-10

protected synchronized Class ? loadClass String name,boolean resolve throws ClassNotFoundException


{
//
Class c=findLoadedClass name
if c==null {
try{
if parent =null {
c=parent.loadClass name,false
}else{
c=findBootstrapClassOrNull name
}
}catch ClassNotFoundException e {
// ClassNotFoundException
//
}
if c==null {
//
// findClass
c=findClass name
}
}
if resolve {
resolveClass c
}
return c
}

[1] HotSpot MRP Maxine Java


Bootstrap ClassLoader Java C++ HotSpot
JRockit J9 Bootstrap ClassLoader Java
JNI C C++ Bootstrap ClassLoader

[2] defineClass “java.lang”

“java.lang.SecurityException Prohibited package name java.lang”


7.4.3
Java
Java
3 “ ”

“ ” —— JDK 1.2
JDK 1.2 java.lang.ClassLoader
JDK 1.0 Java
JDK 1.2 java.lang.ClassLoader
protected findClass java.lang.ClassLoader
loadClass
loadClassInternal loadClass

loadClass
JDK 1.2 loadClass
findClass loadClass
findClass

“ ”

“ ” API

JNDI JNDI Java


JDK 1.3 rt.jar JNDI
ClassPath
JNDI SPI,Service Provider Interface “ ”

Java
Thread Context ClassLoader java.lang.Thread
setContextClassLoaser

“ ” JNDI
SPI

Java SPI
JNDI JDBC JCE JAXB JBI

“ ”
“ ” “ ” HotSwap Hot
Deployment U
Sun JSR-294 JSR-277
[1] [2]
JCP JSR-
291 OSGi R4.2 Sun Java Jigsaw
OSGi “ ” Java [3]
OSGi
OSGi Bundle
Bundle Bundle

OSGi
OSGi

1 java.*

3 Import Export Bundle

4 Bundle ClassPath

5 Fragment Bundle Fragment Bundle

6 Dynamic Import Bundle Bundle

“ ”
“ ”
OSGi
Java
OSGi OSGi

[1]JSR-294 Improved Modularity Support in the Java Programming Language Java

[2]JSR-277 Java Module System Java


[3] Java OSGi
OSGi Equinox
7.5
“ ” “ ” “ ” “ ” “ ”5

6 7 Class
8
Class
8

8.1
Java “ ” “ ”

Java
Facade Java
[1]

Java

[1] Sun Classic VM


BEA JRockit
8.2
Stack Frame
Virtual Machine Stack [1]

Code [2]

Current Stack
Frame Current Method
8-1

8-1
8.2.1
Local Variable Table
Java Class Code max_locals

Variable Slot Slot


Slot Slot
boolean byte char short int float reference returnAddress 8
32 “ Slot 32
” Slot
64 64 Slot
Slot 32

Java Slot
32 Java 32 boolean byte char short
int float reference [3]
returnAddress 8 6 Java
Java Java
7 reference

Java

Java [4]
8
returnAddress jsr jsr_w ret
Java

64 Slot
Java
reference 32 64 64 long double
long double “long double
” long double 32
Java
Slot [5]

0
Slot 32 n n Slot 64
n n+1 Slot 64
Slot Java

static 0 Slot
“this”
1 Slot
Slot

Slot
PC
Slot
Slot
8-1 8-3 3

8-1 Slot

public static void main String[]args {


byte[]placeholder=new byte[64*1024*1024]
System.gc
}

8-1 64MB
“-verbose gc”
System.gc 64MB

[GC 66846K- 65824K 125632K 0.0032678 secs]


[Full GC 65824K- 65746K 125632K 0.0064131 secs]

placeholder System.gc
placeholder placeholder
8-2

8-2 Slot

public static void main String[]args {


{
byte[]placeholder=new byte[64*1024*1024]
}
System.gc
}

placeholder
System.gc placeholder
64MB

[GC 66846K- 65888K 125632K 0.0009397 secs]


[Full GC 65888K- 65746K 125632K 0.0051574 secs]

System.gc
“int a=0 ” 8-3

8-3 Slot

public static void main String[]args {


{
byte[]placeholder=new byte[64*1024*1024]
}
int a=0
System.gc
}
[GC 66401K- 65778K 125632K 0.0035471 secs]
[Full GC 65778K- 218K 125632K 0.0140596 secs]

8-1 8-3 placeholder


Slot placeholder
placeholder placeholder
Slot GC Roots

null int a=0


Slot
JIT
“ ” Java Practical Java “
null”

8-1 8-3 null


null

8-3
null
6 6.5 “ ”

JIT
null JIT null
GC Roots
8-2 JIT System.gc
8-3

“ ” 7

Java 0 false
8-4

8-4

public static void main String[]args {


int a
System.out.println a
}
[1] 2.2
[2] 6.3.7
[3]Java reference 32 64
64
32 reference
[4] C++ RTTI
C++ Java

[5] Java “long double ”


12
8.2.2
Operand Stack Last In First
Out,LIFO Code
max_stacks Java long
double 32 1 64 2
max_stacks

iadd
int int

iadd
int long float iadd

8-2

8-2
Java “ ” “ ”
8.2.3
[1]

Dynamic Linking 6 Class

8.3

[1] 2
8.2.4

Normal Method Invocation Completion

Java athrow

Abrupt Method Invocation Completion

PC

PC
8.2.5
8.3

Class
Class
Java
Java

8.3.1
Class

Resolution

Java “ ”

Java 5

invokestatic

invokespecial init

invokevirtual

invokeinterface

invokedynamic
4 Java invokedynamic

invokestatic invokespecial
4

final 8-5
sayHello StaticResolution

8-5
/**
*
*
*@author zzm
*/
public class StaticResolution{
public static void sayHello {
System.out.println "hello world"
}
public static void main String[]args {
StaticResolution.sayHello
}
}

javap invokestatic
sayHello

D \Develop\ javap-verbose StaticResolution


public static void main java.lang.String[]
Code
Stack=0 Locals=1 Args_size=1
0 invokestatic#31 //Method sayHello V
3 return
LineNumberTable
line 15 0
line 16 3

Java invokestatic invokespecial


final final invokevirtual

Java final

Dispatch [1]

[1] “ ”
8.3.2
Java Java 3

“ ” “ ” Java

1.
[1]

Overload
8-6

8-6

package org.fenixsoft.polymorphic
/**
*
*@author zzm
*/
public class StaticDispatch{
static abstract class Human{
}
static class Man extends Human{
}
static class Woman extends Human{
}
public void sayHello Human guy {
System.out.println "hello,guy "
}
public void sayHello Man guy {
System.out.println "hello,gentleman "
}
public void sayHello Woman guy {
System.out.println "hello,lady "
}
public static void main String[]args {
Human man=new Man
Human woman=new Woman
StaticDispatch sr=new StaticDispatch
sr.sayHello man
sr.sayHello woman
}
}

hello,guy
hello,guy

8-6 Java
Human

Human man=new Man

“Human” Static Type


Apparent Type “Man” Actual Type
//
Human man=new Man
man=new Woman
//
sr.sayHello Man man
sr.sayHello Woman man

8-6 main
sayHello “sr”

Javac
sayHello Human
main invokevirtual

“ ” “ ” 0 1
“ ”
8-
7 “ ”

8-7

package org.fenixsoft.polymorphic
public class Overload{
public static void sayHello Object arg {
System.out.println "hello Object"
}
public static void sayHello int arg {
System.out.println "hello int"
}
public static void sayHello long arg {
System.out.println "hello long"
}
public static void sayHello Character arg {
System.out.println "hello Character"
}
public static void sayHello char arg {
System.out.println "hello char"
}
public static void sayHello char……arg {
System.out.println "hello char……"
}
public static void sayHello Serializable arg {
System.out.println "hello Serializable"
}
public static void main String[]args {
sayHello 'a'
}
}

hello char

'a' char char


sayHello char arg

hello int

'a' 97
'a' Unicode 97 int
sayHello int arg
hello long

'a' 97 97L
long float double
char- int- long- float- double
byte short char byte short
sayHello long arg

hello Character

'a' java.lang.Character
Character sayHello Character arg

hello Serializable

hello
Serializable java.lang.Serializable java.lang.Character

char int Character Integer


Character java.lang.Comparable Character
Serializable Comparable Character

sayHello Comparable
Character 'a' sayHello Serializable arg

hello Object

char
null
sayHello Object arg

hello char……

7
'a' char
int Character Object
char int
[2]

8-7 Java

2.

[3]
—— Override Man Woman sayHello
8-8

8-8

package org.fenixsoft.polymorphic
/**
*
*@author zzm
*/
public class DynamicDispatch{
static abstract class Human{
protected abstract void sayHello
}
static class Man extends Human{
@Override
protected void sayHello {
System.out.println "man say hello"
}
}
static class Woman extends Human{
@Override
protected void sayHello {
System.out.println "woman say hello"
}
}
public static void main String[]args {
Human man=new Man
Human woman=new Woman
man.sayHello
woman.sayHello
man=new Woman
man.sayHello
}
}

man say hello


woman say hello
woman say hello

Java

Human man
woman sayHello man
Java
javap
8-9

8-9 main
public static void main java.lang.String[]
Code
Stack=2 Locals=3 Args_size=1
0 new#16 //class org/fenixsoft/polymorphic/Dynamic-
Dispatch $Man
3 dup
4 invokespecial#18 //Method org/fenixsoft/polymorphic/Dynamic-
Dispatch $Man." init " V
7 astore_1
8 new#19 //class org/fenixsoft/polymorphic/Dynamic-
Dispatch $Woman
11 dup
12 invokespecial#21 //Method org/fenixsoft/polymorphic/DynamicDispa
tch $Woman." init " V
15 astore_2
16 aload_1
17 invokevirtual#22 //Method org/fenixsoft/polymorphic/Dynamic-
Dispatch $Human.sayHello V
20 aload_2
21 invokevirtual#22 //Method org/fenixsoft/polymorphic/Dynamic-
Dispatch $Human.sayHello V
24 new#19 //class org/fenixsoft/polymorphic/Dynamic-
Dispatch $Woman
27 dup
28 invokespecial#21 //Method org/fenixsoft/polymorphic/Dynam
icDispatch $Woman." init " V
31 astore_1
32 aload_1
33 invokevirtual#22 //Method org/fenixsoft/polymorphic/
DynamicDispatch $Human.sayHello V
36 return

0 15 man woman Man Woman


1 2 Slot

Human man=new Man


Human woman=new Woman

16 21 16 20
sayHello Receiver 17 21

invokevirtual 22
Human.sayHello
invokevirtual invokevirtual

1 C

2 C

java.lang.IllegalAccessError

3 C 2

4 java.lang.AbstractMethodError

invokevirtual
invokevirtual
Java

3.

Java
8-10 Father Son “ ”

8-10

/**
*
*@author zzm
*/
public class Dispatch{
static class QQ{}
static class_360{}
public static class Father{
public void hardChoice QQ arg {
System.out.println "father choose qq"
}
public void hardChoice _360 arg {
System.out.println "father choose 360"
}
}
public static class Son extends Father{
public void hardChoice QQ arg {
System.out.println "son choose qq"
}
public void hardChoice _360 arg {
System.out.println "son choose 360"
}
}
public static void main String[]args {
Father father=new Father
Father son=new Son
father.hardChoice new_360
son.hardChoice new QQ
}
}

father choose 360


son choose qq

main hardChoice hardChoice

Father Son QQ 360


invokevirtual
Father.hardChoice 360 Father.hardChoice QQ
Java

“son.hardChoice new
QQ ” invokevirtual
hardChoice QQ
“QQ” “ QQ” “ QQ”

Father Son Java

Java 1.8 Java


“ Java ”
C# 3.0 Java C#4.0 dynamic
Java
JavaScript Java
JDK 1.7 JSR-292[4]
JDK 1.7
invokedynamic
JDK 1.7

4.

“ ” “ ”

“ ”
Vritual Method Table vtable
invokeinterface ——Inteface Method Table itable
8-10
8-3
8-3

8-3 Son Father Son Father


Son Father Object
Object Object

“ ”
Inline Cache “ ” Class
Hierarchy Analysis,CHA Guarded Inlining “ ”
11

[1] Dispatch “Method


Overload Resolution” “ ”
[2] Java §15.12.2.5 Choosing the Most
Specific Method
[3]

[4]JSR-292 Supporting Dynamically Typed Languages on the Java Platform Java


8.3.3
Java Sun Java JDK 7
JDK 7
——invokedynamic JDK 7 “
” Dynamically Typed Language JDK 8
Lambda JDK 7

1.

Java
Java Java JDK 1.7

[1]

APL Clojure Erlang


Groovy JavaScript Jython Lisp Lua PHP Prolog Python Ruby Smalltalk Tcl
C++ Java


/ ” “ ” Java

public static void main String[]args {


int[][][]array=new int[1][0][-1]
}

NegativeArraySizeException Java
NegativeArraySizeException

NoClassDefFoundError
Java

int main void {


int i[1][0][-1] //GCC “size of array is negative”
return 0
}


obj.println "hello world"


“ ”

Java obj java.io.PrintStream


obj PrintStream PrintStream
obj println String PrintStream
——

ECMAScript JavaScript obj


println String

Java println String


CONSTANT_InterfaceMethodref_info
Class

invokevirtual#4 //Method java/io/PrintStream.println Ljava/lang/String V

ECMAScript obj obj

“ ”

“ ”

2.JDK 1.7

Java Java
Java 1997 Java
“ Java
Java ”
Java Clojure Groovy Jython JRuby

Java
JDK 1.7 4 invokevirtual
invokespecial invokestatic invokeinterface
CONSTANT_Methodref_info CONSTANT_InterfaceMethodref_info
Java

Call Site Caching


Java Java
JDK 1.7 JSR-292 invokedynamic java.lang.invoke

3.java.lang.invoke

JDK 1.7 JSR-292 java.lang.invoke [2]


JSR-292

MethodHandle
MethodHandle C/C++ Function Pointer C# Delegate
C/C++

void sort int list[] const int size,int *compare int,int

Java
compare Comparator
Collections.sort

void sort List list,Comparator c

Method Handle Java


8-11 MethodHandle obj
ClassA PrintStream System.out
println

8-11 MethodHandle

import static java.lang.invoke.MethodHandles.lookup


import java.lang.invoke.MethodHandle
import java.lang.invoke.MethodType
/**
*JSR-292 Method Handle
*@author zzm
*/
public class MethodHandleTest{
static class ClassA{
public void println String s {
System.out.println s
}
}
public static void main String[]args throws Throwable{
Object obj=System.currentTimeMillis %2==0?System.out new ClassA
/* obj println
getPrintlnMH obj .invokeExact "icyfenix"
}
private static MethodHandle getPrintlnMH Object reveiver throws Throwable{
/*MethodType “ ” methodType methodType */
MethodType mt=MethodType.methodType void.class,String.class
/*lookup MethodHandles.lookup */
/* Java this bindTo
*/
return lookup .findVirtual reveiver.getClass "println" mt .bindTo reveiver
}
}

getPrintlnMH invokevirtual
Class
MethodHandle “ ”
MethodHandle

void sort List list,MethodHandle compare

MethodHandle

Java MethodHandle Reflection

Reflection MethodHandle Reflection


Java MethodHandle
MethodHandles.lookup 3 ——findStatic findVirtual findSpecial
invokestatic invokevirtual invokeinterface invokespecial
Reflection API

Reflection java.lang.reflect.Method MethodHandle


java.lang.invoke.MethodHandle Java
Java
Reflection
MethodHandle

MethodHandle
MethodHandle

MethodHandle Reflection
“ Java ” Reflection API Java
MethodHandle Java Java

4.invokedynamic

JDK 1.7 5
invokedynamic 8-11 MethodHandle
invokedynamic

invokedynamic MethodHandle
4 “invoke*”

Java API Class


MethodHandle invokedynamic

invokedynamic “ ” Dynamic Call Site


CONSTANT_Methodref_info JDK
1.7 CONSTANT_InvokeDynamic_info 3
Bootstrap Method BootstrapMethods
MethodType java.lang.invoke.CallSite
CONSTANT_InvokeDynamic_info
CallSite
8-12

8-12 invokedynamic

import static java.lang.invoke.MethodHandles.lookup


import java.lang.invoke.CallSite
import java.lang.invoke.ConstantCallSite
import java.lang.invoke.MethodHandle
import java.lang.invoke.MethodHandles
import java.lang.invoke.MethodType
public class InvokeDynamicTest{
public static void main String[]args throws Throwable{
INDY_BootstrapMethod .invokeExact "icyfenix"
}
public static void testMethod String s {
System.out.println "hello String "+s
}
public static CallSite BootstrapMethod MethodHandles.Lookup lookup,String name,MethodType mt throws Throwable{
return new ConstantCallSite lookup.findStatic InvokeDynamicTest.class,name,mt
}
private static MethodType MT_BootstrapMethod {
return MethodType
.fromMethodDescriptorString
" Ljava/lang/invoke/MethodHandles $Lookup Ljava/lang/String Ljava/lang/invoke/MethodType Ljava/lang/invoke/CallSite "
null
}
private static MethodHandle MH_BootstrapMethod throws Throwable{
return lookup .findStatic InvokeDynamicTest.class "BootstrapMethod" MT_BootstrapMethod
}
private static MethodHandle INDY_BootstrapMethod throws Throwable{
CallSite cs= CallSite MH_BootstrapMethod .invokeWithArguments lookup "testMethod"
MethodType.fromMethodDescriptorString " Ljava/lang/String V" null
return cs.dynamicInvoker
}
}

MethodHandleTest
invokedynamic Java
Java Java Javac
invokedynamic java.dyn.InvokeDynamic
Java invokedynamic
John Rose Da Vinci Machine Project Leader
invokedynamic INDY [3]

INDY

INDY 8-13
javap

8-13 invokedynamic 2

Constant pool
#121=NameAndType#33 #30//testMethod Ljava/lang/String V
#123=InvokeDynamic#0 #121//#0 testMethod Ljava/lang/String V
public static void main java.lang.String[] throws java.lang.Throwable
Code
stack=2 locals=1 args_size=1
0 ldc#23//String abc
2 invokedynamic#123 0//InvokeDynamic#0 testMethod Ljava/lang/String V
7 nop
8 return
public static java.lang.invoke.CallSite BootstrapMethod java.lang.invoke.MethodHandles $Lookup,java.lang.String,java.lang.invoke.MethodType throws
java.lang.Throwable
Code
stack=6 locals=3 args_size=3
0 new#63//class java/lang/invoke/ConstantCallSite
3 dup
4 aload_0
5 ldc#1//class org/fenixsoft/InvokeDynamicTest
7 aload_1
8 aload_2
9 invokevirtual#65//Method java/lang/invoke/MethodHandles $Lookup.findStatic Ljava/lang/Class Ljava/lang/String
Ljava/lang/invoke/MethodType Ljava/lang/invoke/MethodHandle
12 invokespecial#71//Method java/lang/invoke/ConstantCallSite." in it " Ljava/lang/invoke/MethodHandle V
15 areturn

main invokedynamic
123 0 HotSpot invokeinterface 0

2 invokedynamic#123 0//InvokeDynamic#0 testMethod Ljava/lang/String V

123 “#123=InvokeDynamic#0 #121”


CONSTANT_InvokeDynamic_info “#0”
BootstrapMethods 0 javap
BootstrapMethod “#121” 121
CONSTANT_NameAndType_info
“testMethod Ljava/lang/String V”

BootstrapMethod Java INDY


MethodHandles $Lookup findStatic
testMethod MethodHandle ConstantCallSite
invokedynamic testMethod invokedynamic

5.

invokedynamic 4 “invoke*”
Java
8-14

8-14

class GrandFather{
void thinking {
System.out.println "i am grandfather"
}
}
class Father extends GrandFather{
void thinking {
System.out.println "i am father"
}
}
class Son extends Father{
void thinking {
//
// thinking "i am grandfather"
}
}

Java “super”
JDK 1.7

JDK 1.7 Java


ASM Son thinking
GrandFather invokevirtual
JDK 1.7 8-
15

8-15 MethodHandle

import static java.lang.invoke.MethodHandles.lookup


import java.lang.invoke.MethodHandle
import java.lang.invoke.MethodType
class Test{
class GrandFather{
void thinking {
System.out.println "i am grandfather"
}
}
class Father extends GrandFather{
void thinking {
System.out.println "i am father"
}
}
class Son extends Father{
void thinking {
try{
MethodType mt=MethodType.methodType void.class
MethodHandle mh=lookup .findSpecial GrandFather.class "thinking" mt,getClass
mh.invoke this
}catch Throwable e {
}
}
}
public static void main String[]args {
new Test .new Son .thinking
}
}

i am grandfather

[1]
[2] java.dyn java.lang.mh
java.lang.invoke
[3]INDY http://blogs.oracle.com/jrose/entry/a_modest_tool_for_writing
8.4

Java Java

8.4.1
Java “ ” Java JDK 1.0
Class
Java
[ GCJ [1]
GNU Compiler for the Java ] C/C++
CINT [2]
“ ”
Java Java

8-4
8-4

Java Java HLLVM

Abstract Syntax Tree,AST

C/C++
Java

JavaScript
8-4

Java Javac
Java
Java

[1]GCJ http://gcc.gnu.org/java/
[2]CINT http://root.cern.ch/drupal/content/cint
8.4.2
Java [1]
Instruction Set
Architecture,ISA
x86
PC

“1+1”

iconst_1
iconst_1
iadd
istore_0

iconst_1 1 iadd
istore_0 0 Slot

mov eax 1
add eax 1

mov EAX 1 add 1 EAX

[2]

32 80x86 8
32 ARM CPU PDA
16 32
[1] “ ”
Java

[2] Google Android


Dalvik VM
8.4.3
Java
“1+1”
8-16

8-16

public int calc {


int a=100
int b=200
int c=300
return a+b *c
}

Java javap
8-17

8-17

public int calc


Code
Stack=2 Locals=4 Args_size=1
0 bipush 100
2 istore_1
3 sipush 200
6 istore_2
7 sipush 300
10 istore_3
11 iload_1
12 iload_2
13 iadd
14 iload_3
15 imul
16 ireturn
}

javap 2 4 Slot
8-5 8-11 7 8-17

8-5 0
8-6 1

8-7 11
8-8 12

8-9 13
8-10 14

8-11 16

……

HotSpot “fast_”
[1]
[1] 11
8.5

6 7 8 Java
9
9

9.1
Class Class
9.2
4
Java

9.2.1 Tomcat
Java Web Tomcat Jetty WebLogic WebSphere
Web

Web Java

Web Java
10 Spring
10 Spring ——

Web
Java Web Java

JSP Web HotSwap JSP


Java Class JSP
Class ASP PHP JSP
“ ” “ ” Web JSP
“ ” Production Mode WebLogic
JSP

Web ClassPath
Web “ ” ClassPath
“lib” “classes”
Java
Tomcat [1]
Tomcat

Tomcat 3 “/common/*” “/server/*” “/shared/*”


Java Web “/WEB-INF/*” 4 Java

/common Tomcat Web


/server Tomcat Web

/shared Web Tomcat

/WebApp/WEB-INF Web Tomcat


Web

Tomcat
9-1
9-1 Tomcat

3 JDK 3 7
CommonClassLoader CatalinaClassLoader SharedClassLoader
WebappClassLoader Tomcat /common/* /server/*
/shared/* /WebApp/WEB-INF/* Java WebApp Jsp
Web WebApp JSP Jsp
9-1 CommonClassLoader Catalina
ClassLoader SharedClassLoader CatalinaClassLoader SharedClassLoader
WebAppClassLoader SharedClassLoader
WebAppClassLoader JasperLoader JSP
Class JSP
JasperLoader Jsp JSP
HotSwap

Tomcat 6.x tomcat/conf/catalina.properties server.loader


share.loader CatalinaClassLoader SharedClassLoader
CommonClassLoader
loader Tomcat 6.x /common /server /shared
/lib /common
Tomcat
server.loader share.loader Tomcat 5.x

Tomcat “ ”
Tomcat
“ ”
10 Web Spring
Spring Common Shared Spring
/WebApp/WEB-INF
CommonClassLoader SharedClassLoader Spring
7

[1]Tomcat Apache Java Web


http://tomcat.apache.org Tomcat 5.x
Tomcat 6.x /common /server /shared
9.2.2 OSGi
Java “ JEE JBoss
OSGi ” “JEE ” “ ”
OSGi

OSGi [1]
Open Service Gateway Initiative OSGi OSGi Alliance
Java Sun IBM
Java
Java “ ”
Equinox Felix OSGi Java Eclipse IDE
OSGi IBM
Jazz GlassFish jBoss OSGi

OSGi Bundle Java JAR


Java Package Class Bundle
Java Package Import-Package Java
Package Export-Package OSGi Bundle

Export Package Package


Class OSGi
OSGi

OSGi “ ” OSGi Bundle


Bundle
Package Bundle Package Package
Bundle Package Bundle
Package Class Package
Bundle

Bundle Bundle Export-Package


Bundle Export Bundle
Bundle OSGi Bundle
Bundle

Bundle A Bundle B Bundle C


Bundle

Bundle A packageA java.*

Bundle B packageA packageC java.*

Bundle C packageC packageA


Bundle 9-2

9-2 OSGi

OSGi 9-2
OSGi
OSGi 9-2

java.*

Import Export Bundle

Bundle Classpath

Fragment Bundle Fragment Bundle

Dynamic Import Bundle Bundle

9-2 OSGi

OSGi Equinox OSGi


Bundle
Bundle A Bundle B Package B Bundle B
Bundle A Package A Bundle
Bundle A Package B
java.lang.ClassLoader.loadClass synchronized Bundle B
Bundle B Package A
Bundle A

Equinox Bug List Bug[2]

—— osgi.classloader.singleThreadLoads
JDK 1.7
[3]

OSGi

OSGi
OSGi OSGi

[1]OSGi http://www.osgi.org/Main/HomePage
[2]Bug-121737 https://bugs.eclipse.org/bugs/show_bug.cgi?id=121737
[3]JDK 1.7-Upgrade class-loader architecture
http://openjdk.java.net/projects/jdk7/features/#f352
9.2.3
“ ” “ ”
Javassist CGLib ASM JDK javac
“ ” javac Java OpenJDK
langtools/src/share/classes/com/sun/tools/javac [1]
javac
javac Java javac
Web JSP
AOP

Java java.lang.reflect.Proxy
java.lang.reflect.InvocationHandler Spring Bean
Spring Bean
Spring Bean “ ”
Java “ ”

9-1 “hello
world” “welcome”
JDK

9-1

public class DynamicProxyTest{


interface IHello{
void sayHello
}
static class Hello implements IHello{
@Override
public void sayHello {
System.out.println "hello world"
}
}
static class DynamicProxy implements InvocationHandler{
Object originalObj
Object bind Object originalObj {
this.originalObj=originalObj
return
Proxy.newProxyInstance originalObj.getClass .getClassLoader originalObj.getClass .getInterfaces this
}
@Override
public Object invoke Object proxy,Method method,Object[]args throws Throwable{
System.out.println "welcome"
return method.invoke originalObj,args
}
}
public static void main String[]args {
IHello hello= IHello new DynamicProxy .bind new Hello
hello.sayHello
}
}

welcome
hello world

“ ” Proxy.newProxyInstance
IHello new Hello
sun.misc.ProxyGenerator.generateProxyClass
byte[]
main

System.getProperties .put "sun.misc.ProxyGenerator.saveGeneratedFiles" "true"

“$Proxy0.class” Class
9-2

9-2

package org.fenixsoft.bytecode
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy
import java.lang.reflect.UndeclaredThrowableException
public final class $Proxy0 extends Proxy
implements DynamicProxyTest.IHello
{
private static Method m3
private static Method m1
private static Method m0
private static Method m2
public $Proxy0 InvocationHandler paramInvocationHandler
throws
{
super paramInvocationHandler
}
public final void sayHello
throws
{
try
{
this.h.invoke this,m3 null
return
}
catch RuntimeException localRuntimeException
{
throw localRuntimeException
}
catch Throwable localThrowable
{
throw new UndeclaredThrowableException localThrowable
}
}
// equals hashCode toString
// 3 sayHello
static
{
try
{
m3=Class.forName "org.fenixsoft.bytecode.DynamicProxyTest $IHello" .getMethod "sayHello" new Class[0]
m1=Class.forName "java.lang.Object" .getMethod "equals" new Class[]{Class.forName "java.lang.Object" }
m0=Class.forName "java.lang.Object" .getMethod "hashCode" new Class[0]
m2=Class.forName "java.lang.Object" .getMethod "toString" new Class[0]
return
}
catch NoSuchMethodException localNoSuchMethodException
{
throw new NoSuchMethodError localNoSuchMethodException.getMessage
}
catch ClassNotFoundException localClassNotFoundException
{
throw new NoClassDefFoundError localClassNotFoundException.getMessage
}
}
}

java.lang.Object equals hashCode toString


InvocationHandler invoke “this.h”
Proxy InvocationHandler
Method
InvocationHandler.invoke

generateProxyClass
“$Proxy0.class” Class
byte
OpenJDK jdk/src/share/classes/sun/misc sun.misc.ProxyGenerator

[1] OpenJDK 1
9.2.4 Retrotranslator JDK
“ ”
JDK Java C# C++
“ ”

Java JDK Java


JDK 1.5
foreach …… Java
“ ” 24
15 “ ”
1.5 JDK 15
24 JDK JDK 1.5 JDK 1.4 1.3
“Java ” Java
Backporting Tools Retrotranslator [1]

Retrotranslator JDK 1.5 Class JDK 1.4 1.3

JDK 1.5
Retrotranslator

Retrotranslator JDK JDK JDK


JDK 4

Integer.valueOf Float.valueOf
[2]

Java API JDK 1.2 java.util.Collections


JDK 1.5 java.util.concurrent

JDK 1.7
invokedynamic

JDK 1.5 JSR-133 [3]


Java Java
Memory Model,JMM CMS

4 Retrotranslator
JDK
JDK 1.5
java.util.concurrent Doug Lea JDK 1.5
dl.util.concurrent JDK JDK
JDK
Retrotranslator “backport-util-concurrent.jar” “Backport
ot JSR 166” JDK 1.5

JDK Retrotranslator ASM


Class JDK 1.3 JDK
1.4 JDK 1.5
Class 49.0 48.0
JDK 1.5
enum Class CONSTANT_Class_info

“CONSTANT_Enum_info” “ ” enum
Java class interface
Javac
java.lang.Enum values valueOf Java

Retrotranslator “java.lang.Enum”
“net.sf.retrotranslator.runtime.java.lang.Enum_”
ACC_ENUM
values valueOf
9-3
JDK 1.5 Retrotranslator
9-3 Retrotranslator
[1]Retrotranslator http://retrotranslator.sf.net
[2] 10.3
[3]JSR-133 Java Memory Model and Thread Specification Revision Java
9.3

Java
Groovy Console

JDK 1.6 Compiler API Java


JDK 1.6
JSP
BeanShell Script JavaScript Mozilla Rhino [1]

9.3.1
“ ”

JDK JDK JDK 1.4 JDK 1.7

BeanShell Script JavaScript “ ”


Java

“ ”
“ ” “ ” “ ”

“ ”

5 250

[1]Rhino http://www.mozilla.org/rhino/ Rhino JDK 1.6


9.3.2
3

Java

Java

Java

tools.jar Sun JDK/lib


com.sun.tools.javac.Main Java Javac
JAR “ ” Sun JDK
JDK tools.jar JRockit J9 JAR
Java

Java
Java

Java
Class
Java “main ”

Java

System.out
System.err
System.setOut /System.setErr PrintStream

System.out
PrintStream
9.3.3
4
“ ” 9.3.1
2 HotSwapClassLoader 9-3

9-3 HotSwapClassLoader

/**
* br
* defineClass loadByte
* loadClass
*
*@author zzm
*/
public class HotSwapClassLoader extends ClassLoader{
public HotSwapClassLoader {
super HotSwapClassLoader.class.getClassLoader
}
public Class loadByte byte[]classByte {
return defineClass null,classByte 0 classByte.length
}
}

HotSwapClassLoader java.lang.ClassLoader
protected defineClass Java byte[]
Class HotSwapClassLoader loadClass findClass
loadByte

HotSwapClassLoader
9-3

java.lang.System HackSystem
Class byte[]
CONSTANT_Utf8_info 9-4 ClassModifier
byte[] byte[] int String byte[]
9-5 ByteUtils

9-4 ClassModifier

/**
* Class
*@author zzm
*/
public class ClassModifier{
/**
*Class
*/
private static final int CONSTANT_POOL_COUNT_INDEX=8
/**
*CONSTANT_Utf8_info tag
*/
private static final int CONSTANT_Utf8_info=1
/**
* 11 CONSTANT_Utf8_info
*/
private static final int[]CONSTANT_ITEM_LENGTH={-1 -1 -1 5 5 9 9 3 3 5 5 5 5}
private static final int u1=1
private static final int u2=2
private byte[]classByte
public ClassModifier byte[]classByte {
this.classByte=classByte
}
/**
* CONSTANT_Utf8_info
*@param oldStr
*@param newStr
*@return
*/
public byte[]modifyUTF8Constant String oldStr,String newStr {
int cpc=getConstantPoolCount
int offset=CONSTANT_POOL_COUNT_INDEX+u2
for int i=0 i cpc i++ {
int tag=ByteUtils.bytes2Int classByte,offset,u1
if tag==CONSTANT_Utf8_info {
int len=ByteUtils.bytes2Int classByte,offset+u1 u2
offset+= u1+u2
String str=ByteUtils.bytes2String classByte,offset,len
if str.equalsIgnoreCase oldStr {
byte[]strBytes=ByteUtils.string2Bytes newStr
byte[]strLen=ByteUtils.int2Bytes newStr.length u2
classByte=ByteUtils.bytesReplace classByte,offset-u2 u2 strLen
classByte=ByteUtils.bytesReplace classByte,offset,len,strBytes
return classByte
}else{
offset+=len
}
}else{
offset+=CONSTANT_ITEM_LENGTH[tag]
}
}
return classByte
}
/**
*
*@return
*/
public int getConstantPoolCount {
return ByteUtils.bytes2Int classByte,CONSTANT_POOL_COUNT_INDEX,u2
}
}

9-5 ByteUtils

/**
*Bytes
*@author
*/
public class ByteUtils{
public static int bytes2Int byte[]b,int start,int len {
int sum=0
int end=start+len
for int i=start i end i++ {
int n= int b[i] 0xff
n = --len *8
sum=n+sum
}
return sum
}
public static byte[]int2Bytes int value,int len {
byte[]b=new byte[len]
for int i=0 i len i++ {
b[len-i-1]= byte value 8*i 0xff
}
return b
}
public static String bytes2String byte[]b,int start,int len {
return new String b,start,len
}
public static byte[]string2Bytes String str {
return str.getBytes
}
public static byte[]bytesReplace byte[]originalBytes,int offset,int len,byte[]replaceBytes {
byte[]newBytes=new byte[originalBytes.length+ replaceBytes.length-len ]
System.arraycopy originalBytes 0 newBytes 0 offset
System.arraycopy replaceBytes 0 newBytes,offset,replaceBytes.length
System.arraycopy originalBytes,offset+len,newBytes,offset+replaceBytes.length,originalBytes.length-offset-len
return newBytes
}
}

ClassModifier byte[] HotSwapClassLoader.loadByte


byte[] Java HackSystem
Class
HackSystem
9-4 9-5

java.lang.System HackSystem
out err ByteArrayOutputStream
PrintStream ByteArrayOutputStream
getBufferString clearBuffer
System public
System Sytem HackSystem
System HackSystem
9-6

9-6 HackSystem

/**
* JavaClass java.lang.System
* out err System
*
*@author zzm
*/
public class HackSystem{
public final static InputStream in=System.in
private static ByteArrayOutputStream buffer=new ByteArrayOutputStream
public final static PrintStream out=new PrintStream buffer
public final static PrintStream err=out
public static String getBufferString {
return buffer.toString
}
public static void clearBuffer {
buffer.reset
}
public static void setSecurityManager final SecurityManager s {
System.setSecurityManager s
}
public static SecurityManager getSecurityManager {
return System.getSecurityManager
}
public static long currentTimeMillis {
return System.currentTimeMillis
}
public static void arraycopy Object src,int srcPos,Object dest,int destPos,int length {
System.arraycopy src,srcPos,dest,destPos,length
}
public static int identityHashCode Object x {
return System.identityHashCode x
}
// java.lang.System
// System
//
}

4 JavaClassExecuter
JavaClassExecuter
execute Class byte[] java.lang.System
HotSwapClassLoader Class execute
Class
main HackSystem.out
JavaClassExecuter 9-7

9-7 JavaClassExecuter

/**
*JavaClass
*
*@author zzm
*/
public class JavaClassExecuter{
/**
* Java byte br
* byte java.lang.System CONSTANT_Utf8_info HackSystem
* static main String[]args System.out/err
*@param classByte Java byte
*@return
*/
public static String execute byte[]classByte {
HackSystem.clearBuffer
ClassModifier cm=new ClassModifier classByte
byte[]modiBytes=cm.modifyUTF8Constant "java/lang/System" "org/fenixsoft/classloading/execute/HackSystem"
HotSwapClassLoader loader=new HotSwapClassLoader
Class clazz=loader.loadByte modiBytes
try{
Method method=clazz.getMethod "main" new Class[]{String[].class}
method.invoke null,new String[]{null}
}catch Throwable e {
e.printStackTrace HackSystem.out
}
return HackSystem.getBufferString
}
}
9.3.4

Java System.out
TestClass C JSP 9-
8

9-8 JSP

%@page import="java.lang.*"%
%@page import="java.io.*"%
%@page import="org.fenixsoft.classloading.execute.*"%
%
InputStream is=new FileInputStream "c /TestClass.class"
byte[]b=new byte[is.available ]
is.read b
is.close
out.println " textarea style='width 1000 height=800' "
out.println JavaClassExecuter.execute b
out.println " /textarea "
%

JavaExecuter
Class
“ ” Eclipse Java
Eclipse Console

9-4

9-4 JavaClassExecuter
9.4
6 9 Class

4
Class

10
10

11
10

F1

10.1
Java “ ” “ ”
“ ” *.java *.class
JIT Just In Time Compiler
AOT Ahead Of Time Compiler *.java
3

Sun Javac Eclipse JDT ECJ [1]

JIT HotSpot VM C1 C2

AOT GNU Compiler for the Java GCJ [2]


Excelsior JET [3]

3 Java
“ ” “ ”
“ ” Javac
JDK 1.3 Javac -O

Javac Class JRuby Groovy Class


Javac Java
Java “ ”
Java

[1]JDT http://www.eclipse.org/jdt/
[2]GCJ http://gcc.gnu.org/java/
[3]Excelsior JET http://www.excelsior-usa.com/
10.2 Javac
Javac HotSpot
C++ C Java
Java

10.2.1 Javac
Javac JDK_SRC_HOME/langtools/src/share/classes/com/sun/tools/javac [1]

JDK API JDK_SRC_HOME/langtools/src/share/classes/com/sun/*

Eclipse IDE “Compiler_javac” Java


JDK_SRC_HOME/langtools/src/share/classes/com/sun/*
10-1

10-1 Eclipse Javac

“AnnotationProxy Maker.java” “Access Restriction”


Eclipse 10-2
10-2 AnnotationProxyMaker

Eclipse JRE System Library Access


Rules
JAR 10-3

10-3

Javac com.sun.tools.javac.Main main


Javac Eclipse “Debug
Configurations” “Arguments”

Class Java 2
“Compiling for the Java Virtual Machine”
Java Class Class
JDK Javac
ECJ 10.3.1 Sun
Javac 3
3 10-4

10-4 Javac [2]

Javac com.sun.tools.javac.main.JavaCompiler 3
compile compile2 10-5
8 8

10-5 Javac
[1] OpenJDK 1
[2] http://openjdk.java.net/groups/compiler/doc/compilation-overview/index.html
10.2.2
10-5 parseFiles 10-5 1.1

1.

Token

“int a=b+2” 6 int a = b + 2 int


3 Token Javac
com.sun.tools.javac.parser.Scanner

Token Abstract Syntax


Tree,AST
Construct

10-6 Eclipse AST View


Javac
com.sun.tools.javac.parser.Parser
com.sun.tools.javac.tree.JCTree
10-6

2.

10-5
enterTrees 10-5 1.2 Symbol Table
K-V

Javac com.sun.tools.javac.comp.Enter
To Do List
package-info.java
10.2.3
JDK 1.5 Java Annotation Java
JDK 1.6 JSR-269 [1]

API

Round
10-4

API

Javac initPorcessAnnotations
processAnnotations

com.sun.tools.javac.processing.JavacProcessingEnvironment doProcessing
JavaCompiler

[1]JSR-269 Pluggable Annotations Processing API API


10.2.4

int a=1
boolean b=false
char c=2

int d=a+c
int d=b+c
char d=a+c

3
1 Java

C a b c 2 3

1.

Javac
10-5 attribute flow 10-5 3.1 3.2

int a=1+2

“1” “2” “+”


“3” 10-7 Infix Expression
ConstantExpressionValue 3
“a=1+2” “a=3”
CPU
10-7

Javac com.sun.tools.javac.comp.Attr
com.sun.tools.javac.comp.Check

2.

final 10-1

10-1 final

// final
public void foo final int arg {
final int var=0
//do something
}
// final
public void foo int arg {
int var=0
//do something
}

foo final
final arg var
Class 6

CONSTANT_Fieldref_info Access_Flags
Class
final final
Javac
10-5 flow 10-5 3.2
com.sun.tools.javac.comp.Flow

3.

Syntactic Sugar · ·
Peter J.Landin

Java “ ” C# JVM
JDK 1.5 “ ” Java “ ” Java
C#
CLR /
Java
10.3

Javac desugar
com.sun.tools.javac.comp.TransTypes com.sun.tools.javac.comp.Lower

4.

Javac Javac
com.sun.tools.javac.jvm.Gen

init clinit

public protected private

“{}” “static{}”
clinit
clinit clinit
java.lang.Object init init
clinit
Gen.normalizeDefs

StringBuffer StringBuilder JDK 1.5


append

com.sun.tools.javac.jvm.ClassWriter writeClass
Class
10.3 Java


“ ” “ ”
“ ” “ ”

10.3.1
JDK 1.5 Parametersized Type

C++ Template Java


Object
JDK 1.5 HashMap get
Object Java java.lang.Object Object

Object Object
ClassCastException

C# Java C#
IL Intermediate Language
CLR List int List String

Java
Raw Type
Java ArrayList int ArrayList String
Java Java

10-2 Java

10-2

public static void main String[]args {


Map String,String map=new HashMap String,String
map.put "hello" " "
map.put "how are you?" " "
System.out.println map.get "hello"
System.out.println map.get "how are you?"
}
Java Class
Java
10-3

10-3

public static void main String[]args {


Map map=new HashMap
map.put "hello" " "
map.put "how are you?" " "
System.out.println String map.get "hello"
System.out.println String map.get "how are you?"
}

JDK Java
Java
Thinking in Java Bruce Eckel
[1]
JDK 1.5

C#
Java C#
Java
10-4

10-4 1

public class GenericTypes{


public static void method List String list {
System.out.println "invoke method List String list "
}
public static void method List Integer list {
System.out.println "invoke method List Integer list "
}
}

List Integer List String


List E

10-5

10-5 2

public class GenericTypes{


public static String method List String list {
System.out.println "invoke method List String list "
return""
}
public static int method List Integer list {
System.out.println "invoke method List Integer list "
return 1
}
public static void main String[]args {
method new ArrayList String
method new ArrayList Integer
}
}
invoke method List String list
invoke method List Integer list

10-5 10-4 method


[2]
Java

10-5
method Class 6
Class method_info

Class
Class

Java
JCP
Signature LocalVariableTypeTable
Signature
[3]

[4]
49.0
Class Signature

List String List Integer

Sun JDK 1.6 Javac ECJ

Signature
Code

[1] http://www.anyang-window.com.cn/quotthis-is-not-a-genericquot-bruce-eckel-eyes-
of-the-generic-java/
[2] Sun JDK 1.6 Javac Eclipse JDT ECJ
ECJ “Method method List String
has the same erasure method List E as another method in type GenericTypes”
[3] Java 2 JDK 1.5 “§4.4.4 Signatures”
Java 3 “§8.4.2 Method Signature”
Java
ID Java

[4]JDK 1.5 http://jcp.org/aboutJava/communityprocess/maintenance/jsr


924/index.html
10.3.2
Foreach

Java
10-6 10-7

10-6

public static void main String[]args {


List Integer list=Arrays.asList 1 2 3 4
// JDK 1.7 [1]
// List Integer list=[1 2 3 4]
int sum=0
for int i list {
sum+=i
}
System.out.println sum
}

10-7

public static void main String[]args {


List list=Arrays.asList new Integer[]{
Integer.valueOf 1
Integer.valueOf 2
Integer.valueOf 3
Integer.valueOf 4 }
int sum=0
for Iterator localIterator=list.iterator localIterator.hasNext {
int i= Integer localIterator.next .intValue
sum+=i
}
System.out.println sum
}

10-6 5
10-7
Integer.valueOf
Integer.intValue
Iterable

10-8

10-8

public static void main String[]args {


Integer a=1
Integer b=2
Integer c=3
Integer d=3
Integer e=321
Integer f=321
Long g=3L
System.out.println c==d
System.out.println e==f
System.out.println c== a+b
System.out.println c.equals a+b
System.out.println g== a+b
System.out.println g.equals a+b
}

10-8 6
6
“==” equals

[1] Project Coin JDK 1.8 JDK 1.7


10.3.3
C C++
#ifdef C C++
#include Java Java
Java

Java

Java if 10-
9 if Java “ ”
“System.out.println "block 1" ” if
“System.out.println "block 2" ”

10-9 Java

public static void main String[]args {


if true {
System.out.println "block 1"
}else{
System.out.println "block 2"
}
}

Class

public static void main String[]args {


System.out.println "block 1"
}

if
10-10

10-10

public static void main String[]args {


// “Unreachable code”
while false {
System.out.println ""
}
}

Java Java

com.sun.tools.javac.comp.Lower if
Java
Block Java

Java
JDK 1.7 switch try JDK 1.7
Javac Class
10.4
JDK
JDK
11 JIT
JSR-296 API JDK

JDK

Java
11 JDK
JDK
API

10.4.1
Javac Java
Java “ ”
WARNING “ ”
“ ” CheckStyle FindBug Klocwork
Java
API
NameCheckProcessor

CheckStyle NameCheckProcessor Java


Java 3 6.8 Java

Camel Case Name


Java
Javac
[1]

[1] JDK sample/javac/processing


10.4.2
API API
javax.annotation.processing.AbstractProcessor
abstract “process ” Javac
“annotations”
“roundEnv” Round
Element JDK 1.6 javax.lang.model
16 Element Java “ PACKAGE
ENUM CLASS ANNOTATION_TYPE INTERFACE
ENUM_CONSTANT FIELD PARAMETER
LOCAL_VARIABLE EXCEPTION_PARAMETER METHOD
CONSTRUCTOR STATIC_INIT static{}
INSTANCE_INIT {} TYPE_PARAMETER
OTHER ” process
“processingEnv” AbstractProcessor protected
init AbstractProcessor

process Annotations
@SupportedAnnotationTypes @SupportedSourceVersion
“*”
Java

process false Round


JavaCompiler
process false
API
NameCheckProcessor 10-11

10-11 NameCheckProcessor

// "*" Annotations
@SupportedAnnotationTypes "*"
// JDK 1.6 Java
@SupportedSourceVersion SourceVersion.RELEASE_6
public class NameCheckProcessor extends AbstractProcessor{
private NameChecker nameChecker
/**
*
*/
@Override
public void init ProcessingEnvironment processingEnv {
super.init processingEnv
nameChecker=new NameChecker processingEnv
}
/**
*
*/
@Override
public boolean process Set ?extends TypeElement annotations,RoundEnvironment roundEnv {
if roundEnv.processingOver {
for Element element roundEnv.getRootElements
nameChecker.checkNames element
}
return false
}
}
NameCheckProcessor JDK 1.6
“ ” process Round
RootElement NameChecker NameChecker
10-12

10-12 NameChecker

/**
* br
* WARNING
*/
public class NameChecker{
private final Messager messager
NameCheckScanner nameCheckScanner=new NameCheckScanner
NameChecker ProcessingEnvironment processsingEnv {
this.messager=processsingEnv.getMessager
}
/**
* Java Java 3 6.8 Java
*
* ul
* li
* li
* li
* ul
* li
* li
* /ul
* /ul
*/
public void checkNames Element element {
nameCheckScanner.scan element
}
/**
* JDK 1.6 ElementScanner6 br
* Visitor
*/
private class NameCheckScanner extends ElementScanner6 Void,Void {
/**
* Java
*/
@Override
public Void visitType TypeElement e,Void p {
scan e.getTypeParameters p
checkCamelCase e,true
super.visitType e,p
return null
}
/**
*
*/
@Override
public Void visitExecutable ExecutableElement e,Void p {
if e.getKind ==METHOD {
Name name=e.getSimpleName
if
name.contentEquals e.getEnclosingElement .getSimpleName
messager.printMessage WARNING " ""+name+"" " e
checkCamelCase e,false
}
super.visitExecutable e,p
return null
}
/**
*
*/
@Override
public Void visitVariable VariableElement e,Void p {
// Variable
if e.getKind ==ENUM_CONSTANT||e.getConstantValue =null||heuristicallyConstant e
checkAllCaps e
else
checkCamelCase e,false
return null
}
/**
*
*/
private boolean heuristicallyConstant VariableElement e {
if e.getEnclosingElement .getKind ==INTERFACE
return true
else if e.getKind ==FIELD e.getModifiers .containsAll EnumSet.of PUBLIC,STATIC,FINAL
return true
else{
return false
}
}
/**
* Element
*/
private void checkCamelCase Element e,boolean initialCaps {
String name=e.getSimpleName .toString
boolean previousUpper=false
boolean conventional=true
int firstCodePoint=name.codePointAt 0
if Character.isUpperCase firstCodePoint {
previousUpper=true
if initialCaps {
messager.printMessage WARNING " ""+name+"" " e
return
}
}else if Character.isLowerCase firstCodePoint {
if initialCaps {
messager.printMessage WARNING " ""+name+"" " e
return
}
}else
conventional=false
if conventional {
int cp=firstCodePoint
for int i=Character.charCount cp i name.length i+=Character.charCount cp {
cp=name.codePointAt i
if Character.isUpperCase cp {
if previousUpper {
conventional=false
break
}
previousUpper=true
}else
previousUpper=false
}
}
if conventional
messager.printMessage WARNING " ""+name+"" Camel Case Names " e
}
/**
*
*/
private void checkAllCaps Element e {
String name=e.getSimpleName .toString
boolean conventional=true
int firstCodePoint=name.codePointAt 0
if Character.isUpperCase firstCodePoint
conventional=false
else{
boolean previousUnderscore=false
int cp=firstCodePoint
for int i=Character.charCount cp i name.length i+=Character.charCount cp {
cp=name.codePointAt i
if cp== int '_' {
if previousUnderscore {
conventional=false
break
}
previousUnderscore=true
}else{
previousUnderscore=false
if Character.isUpperCase cp Character.isDigit cp
{
conventional=false
break
}
}
}
}
if conventional
messager.printMessage WARNING " ""+name+"" " e
}
}
}

NameChecker
190 javax.lang.model.util.ElementScanner6 NameCheckScanner
Visitor visitType visitVariable
visitExecutable 3 visit
checkCamelCase checkAllCaps

NameCheckProcessor NameChecker
10-13 “ ”
Javac
Warning

10-13

public class BADLY_NAMED_CODE{


enum colors{
red,blue,green
}
static final int_FORTY_TWO=42
public static int NOT_A_CONSTANT=_FORTY_TWO
protected void BADLY_NAMED_CODE {
return
}
public void NOTcamelCASEmethodNAME {
return
}
}
10.4.3
Javac “-processor”
-XprintRounds -XprintProcessorInfo
NameCheckProcessor
10-14

10-14

D \src javac org/fenixsoft/compile/NameChecker.java


D \src javac org/fenixsoft/compile/NameCheckProcessor.java
D \src javac-processor org.fenixsoft.compile.NameCheckProcessor org/fenixsoft/compile/BADLY_NAMED_CODE.java
org\fenixsoft\compile\BADLY_NAMED_CODE.java 3 "BADLY_NAMED_CODE" Camel Case Names
public class BADLY_NAMED_CODE{
^
org\fenixsoft\compile\BADLY_NAMED_CODE.java 5 "colors"
enum colors{
^
org\fenixsoft\compile\BADLY_NAMED_CODE.java 6 "red"
red,blue,green
^
org\fenixsoft\compile\BADLY_NAMED_CODE.java 6 "blue"
red,blue,green
^
org\fenixsoft\compile\BADLY_NAMED_CODE.java 6 "green"
red,blue,green
^
org\fenixsoft\compile\BADLY_NAMED_CODE.java 9 "_FORTY_TWO"
static final int_FORTY_TWO=42
^
org\fenixsoft\compile\BADLY_NAMED_CODE.java 11 "NOT_A_CONSTANT"
public static int NOT_A_CONSTANT=_FORTY_TWO
^
org\fenixsoft\compile\BADLY_NAMED_CODE.java 13 "Test"
protected void Test {
^
org\fenixsoft\compile\BADLY_NAMED_CODE.java 17 "NOTcamelCASEmethodNAME"
public void NOTcamelCASEmethodNAME {
^
10.4.4
NameCheckProcessor JSR-269 API
API Hibernate Hibernate Validator
Annotation Processor
[1]
NameCheckProcessor
getter setter Project Lombok [2]

[1] http://www.hibernate.org/subprojects/validator.html
[2] http://projectlombok.org/
10.5
Java
Java /

“ ” Javac
Java “ ”
“ ”
JIT
11
11

F1

11.1
Sun HotSpot IBM J9 Java
Interpreter
“ ” Hot Spot Code

Just In Time Compiler JIT

Java Java

Java
Implementation Specific
HotSpot HotSpot
11.2 HotSpot
HotSpot

HotSpot

HotSpot

11.2.1
Java
HotSpot J9 [1]

“ ”

“ ” Uncommon Trap Deoptimization


C1 [2]
“ ”
11-1

11-1

HotSpot Client Compiler Server Compiler


C1 C2 Opto HotSpot Sun
JDK 1.7
HotSpot
“-client” “-server”
Client Server

Client Compiler Server Compiler


“ ” Mixed Mode “-Xint”
“ ” Interpreted Mode
“-Xcomp” “ ” Compiled Mode [3]

“-version” 3 11-1

11-1

C \ java-version
java version"1.6.0_22"
Java TM SE Runtime Environment build 1.6.0_22-b04
Dynamic Code Evolution 64-Bit Server VM build 0.2-b02-internal 19.0-b04-internal,mixed mode
C \ java-Xint-version
java version"1.6.0_22"
Java TM SE Runtime Environment build 1.6.0_22-b04
Dynamic Code Evolution 64-Bit Server VM build 0.2-b02-internal 19.0-b04-internal,interpreted mode
C \ java-Xcomp-version
java version"1.6.0_22"
Java TM SE Runtime Environment build 1.6.0_22-b04
Dynamic Code Evolution 64-Bit Server VM build 0.2-b02-internal 19.0-b04-internal,compiled mode

HotSpot Tiered Compilation [4]

JDK 1.6 JDK 1.7 Server

0 Profiling 1

1 C1

2 2 C2

Client Compiler Server Compiler


Client Compiler Server Compiler

[1] JRockit
“ ”

[2] Client Compiler C1 Server Compiler C2


[3] Sun HotSpot -Xcomp
[4]Tiered Compilation JDK 1.6 JDK 1.7 -XX
+TieredCompilation Server
Server Compiler
Server Compiler
http://weblogs.java.net/blog/forax/archive/2010/09/04/tiered-compilation
11.2.2
“ ”

“ ”

“ ”

JIT

On
Stack Replacement OSR

“ ” “
” “ ” “ ”

Hot Spot Detection


[1]

Sample Based Hot Spot Detection

“ ”

Counter Based Hot Spot Detection

“ ”

HotSpot ——
Invocation Counter Back Edge
Counter

JIT
Client 1500 Server 10 000
-XX CompileThreshold
JIT
1

JIT 11-2
11-2

Counter Decay
Counter Half Life Time
-XX -UseCounterDecay

-XX CounterHalfLifeTime

——
[2]
“ ” Back Edge
OSR

HotSpot -
XX CompileThreshold -XX BackEdgeThreshold
-XX OnStackReplacePercentage

Client

CompileThreshold ×OSR OnStackReplacePercentage /100

OnStackReplacePercentage 933 Client


13995

Server

CompileThreshold × OSR OnStackReplacePercentage -


InterpreterProfilePercentage /100

OnStackReplacePercentage 140 InterpreterProfilePercentage 33


Server 10700

OSR
11-3
11-3

11-2 11-3 Client VM


Server VM
HotSpot MethodOop.hpp methodOop
Java Java
32 bit
from_compiled_entry from_interpreted_entry

[1] “ ” Trace
FireFox TraceMonkey Dalvik JIT

[2]
11.2.3
OSR

-XX -BackgroundCompilation
JIT

Server Compiler Client


Compiler Client Compiler

High-
Level Intermediate Representaion,HIR HIR Static Single Assignment,SSA
HIR

HIR

HIR Low-Level
Intermediate Representation,LIR HIR
HIR

Linear Scan Register Allocation LIR


LIR Peephole Client Compiler
11-4

11-4 Client Compiler


Server Compiler
GNU C++ -O2
Dead Code Elimination
Loop Unrolling Loop Expression Hoisting
Common Subexpression Elimination Constant Propagation
Basic Block Reordering Java
Range Check Elimination Null Check Elimination

Client Compiler
Guarded Inlining Branch Frequency Prediction

Server Compiler
RISC Server Compiler
Client Compiler

Server

JIT

Java HotSpot
“ ”JIT
11.2.4

Debug FastDebug Product


1 JDK
SKIP_DEBUG_BUILD SKIP_FASTDEBUG_BUILD false OpenJDK
FastDebug JDK JDK 6u25 Oracle FastDebug JDK
11-2 Java

11-2

public static final int NUM=15000


public static int doubleValue int i {
// JIT
for int j=0 j 100000 j++
return i*2
}
public static long calcSum {
long sum=0
for int i=1 i =100 i++ {
sum+=doubleValue i
}
return sum
}
public static void main String[]args {
for int i=0 i NUM i++ {
calcSum
}
}

-XX +PrintCompilation
11-3 “%”
OSR

11-3

VM option'+PrintCompilation'
310 1 java.lang.String charAt 33 bytes
329 2 org.fenixsoft.jit.Test calcSum 26 bytes
329 3 org.fenixsoft.jit.Test doubleValue 4 bytes
332 1%org.fenixsoft.jit.Test main@5 20 bytes

11-3 main calcSum doubleValue


-XX +PrintInlining
11-4

11-4

VM option'+PrintCompilation'
VM option'+PrintInlining'
273 1 java.lang.String charAt 33 bytes
291 2 org.fenixsoft.jit.Test calcSum 26 bytes
@9 org.fenixsoft.jit.Test doubleValue inline hot
294 3 org.fenixsoft.jit.Test doubleValue 4 bytes
295 1%org.fenixsoft.jit.Test main@5 20 bytes
@5 org.fenixsoft.jit.Test calcSum inline hot
@9 org.fenixsoft.jit.Test doubleValue inline hot
11-4 doubleValue calcSum
calcSum main main
main calcSum doubleValue
main

0 1
[1]

32 80x86 hsdis-i386
hsdis-amd64 hsdis-sparc hsdis-sparcv9 [2]

JRE/bin/client /server jvm.dll


-XX +PrintAssembly
4.2.7

HSDIS -XX +PrintOptoAssembly Server VM -


XX +PrintLIR Client VM 11-2
-XX +PrintOptoAssembly 11-5
-XX +PrintOptoAssembly
JIT

11-5

……
000 B1 #N1 -BLOCK HEAD IS JUNK Freq 1
000 pushq rbp
subq rsp #16#Create frame
nop#nop for patch_verified_entry
006 movl RAX,RDX#spill
008 sall RAX #1
00a addq rsp 16#Destroy frame
popq rbp
testl rax [rip+#offset_to_poll_page]#Safepoint poll for GC
……

-XX +PrintAssembly Debug FastDebug


Product -XX
+UnlockDiagnosticVMOptions

-XX +PrintCFGToFile Client Compiler -XX PrintIdealGraphFile


Server Compiler C1
HIR LIR
Java HotSpot Client Compiler Visualizer [3]
Client Compiler Ideal Graph
Visualizer [4]
Server Compiler Server Compiler
JIT

Server Compiler Ideal SSA Program


Dependence Graph Java JVM “-XX PrintIdealGraphLevel=2-XX
PrintIdealGraphFile=ideal.xml” ideal.xml Server
Compiler Ideal Graph Visualizer

Ideal Graph Visualizer ideal.xml Outline


11-5 11-2
doubleValue OSR
11-2 doubleValue
CPU
Java

11-5

Ideal “After Parsing”


JIT Java
“After Parsing” Server Compiler
Ideal
11-6 Basic Block

11-2 doubleValue
Java
Java Safepoint
doubleValue

2 j=0 Safepoint 4

3 j++
4 j 100000 3

5 i=i*2 Safepoint

11-6 1

Ideal Graph Visualizer 11-7

Outline “Difference to current graph”


Ideal
“After Parsing” “PhaseIdealLoop 1” Ideal “PhaseIdealLoop
1” 11-8

11-7 2
11-8 3

“After Parsing” “Final Code” doubleValue


Ideal Java
“Final Code” Safepoint

CFG IdealGraph Debug FastDebug


Product

[1] http://wikis.sun.com/display/HotSpotInternals/PrintAssembly
[2]HSDIS
http://hg.openjdk.java.net/jdk7/hotspot/hotspot/file/tip/src/share/tools/hsdis/
32 80x86 ITeye
http://hllvm.group.iteye.com/group/share
[3] http://java.net/projects/c1visualizer/
[4] http://ssw.jku.at/General/Staff/TW/igv.html
11.3
Java

JDK 1.3
Javac -O
Javac [1]
HotSpot

11.3.1
Sun Wiki HotSpot
[2]
11-1
Java Java
“ ”

Java
Java 11-6
[3]

11-6

static class B{
int value
final int get {
return value
}
}
public void foo {
y=b.get
//……do stuff……
z=b.get
sum=y+z
}

Java Java

11-6
Method Inlining

11-7

11-7

public void foo {


y=b.value
//……do stuff……
z=b.value
sum=y+z
}

Redundant Loads Elimination


“dostuff……” b.value “z=b.value” “z=y”
“y=b.value” y b.value b
b.value
Common Subexpression Elimination 11-8

11-8

public void foo {


y=b.value
//……do stuff……
z=y
sum=y+z
}

Copy Propagation
“z” “y” “y” “z”
11-9
11-9

public void foo {


y=b.value
//……do stuff……
y=y
sum=y+y
}

Dead Code Elimination


“Dead Code”
11-9 “y=y” 11-10

11-10

public void foo {


y=b.value
//……do stuff……
sum=y+y
}

11-10 11-6

[1]

[2] http://wikis.sun.com/display/HotSpotInternals/PerformanceTacticIndex
[3]
http://download.oracle.com/docs/cd/E13150_01/jrockit_jvm/jrockit/geninfo/diagnos/underst_jit.html
11.3.2

E E
E
E
Local Common Subexpression Elimination
Global Common
Subexpression Elimination

int d= c * b *12+a+ a+b * c

Javac 11-11
Java

11-11

iload_2//b
imul// b * c
bipush 12// 12
imul// c * b *12
iload_1//a
iadd// c * b *12+a
iload_1//a
iload_2//b
iload_3//c
imul// b * c
iadd// a+b * c
iadd// c * b *12+a+ a+b * c
istore 4

“c * b” “b
* c” b c

int d=E*12+a+ a+E

Algebraic Simplification

int d=E*13+a*2

“ ” Java 2006
“ ”
11.3.3
Array Bounds Checking Elimination
Java
C C++ foo[] Java
foo[i] i i =0 i foo.length
java.lang.ArrayIndexOutOfBoundsException

“ ”
foo[3] foo.length “3”

[0 foo.length

Java
C/C++ ArrayIndexOutOfBoundsException
NullPointException ArithmeticException C/C++
Segment Fault Window “xxx
Read/Write”
Java C/C++
Java C/C++

—— Java
foo
value Java foo.value

if foo =null {
return foo.value
}else{
throw new NullPointException
}

try{
return foo.value
}catch segment_fault {
uncommon_trap
}

Segment Fault uncommon_trap


foo value foo
foo NullPointException
foo
foo
HotSpot “ ” Profile

Autobox Elimination
Safepoint Elimination Dereflection
11.3.4

11-
12 testInline

“Dead Code” foo testInline

11-12

public static void foo Object obj {


if obj =null {
System.out.println "do something"
}
}
public static void testInline String[]args {
Object obj=null
foo obj
}

“ ”
Java

Java

8 Java
invokespecial invokestatic
4 Java

final invokevirtual
Java Java

11-7 “b.get ” “b.value” b


ParentB SubB get
get get

Java Java
Java
“ ”
final

Java
“ ” Class Hierarchy Analysis,CHA
CHA

“ ” Guard Slow Path Guarded


Inlining

CHA
Inline Cache


” “ ”
11.3.5
Escape Analysis Java

Stack Allocation Java Java


Java Java

Synchronization Elimination

Scalar Replacement Scalar


Java int long reference

Aggregate Java Java

1999 Sun JDK 1.6

“ ” HotSpot
HotSpot
MicroBenchmarks

Server Compiler [1]

JDK 1.6 Update 18

-XX +DoEscapeAnalysis
-XX +PrintEscapeAnalysis
-XX +EliminateAllocations
+XX +EliminateLocks -XX +PrintEliminateAllocations

[1] JDK 1.6 Update 23 Server Compiler


11.4 Java C/C++
C/C++ Java Java “
” Java
Java
Java C/C++
[1]

Java C/C++
Java C/C++ C/C++ Java
API
“ ” “ ”

Java C/C++

Java

Java virtual C/C++


C/C++
C/C++

Java

Java
[2]
C/C++
C/C++

Java C/C++ Java C/C++


Java
“ ” Java

Java C/C++
C/C++ Alias Analysis Java Java
ClassA ClassB objA objB

void foo ClassA objA,ClassB objB {


objA.x=123
objB.y=456
// objB.y objA.x 123
print objA.x
}

objA objB
objB.y objA.x
objA.x 123

Java C/C++
Call
Frequency Prediction Branch Frequency Prediction
Untaken Branch Pruning Java

[1]C/C++ Java
“ ”

[2]Java
C/C++
11.5
10 11 Java
Javac JIT

HotSpot
JIT
Java
12 Java

13
12 Java
Amdahl [1]

“ ”

12.1

I/O

“ ”
“ ”

Transactions
Per Second,TPS
TPS

Java Java
[2]

Java

“ ” Java

[1]Amdahl

[2] JavaCard
12.2
Java

“ ” “ ”

“ ”
I/O

Cache

Cache Coherence
Main
Memory 12-1

MSI MESI Illinois Protocol MOSI Synapse Firefly


Dragon Protocol “ ”

Java

12-1

Out-Of-Order Execution
Java Instruction Reorder
12.3 Java
Java Java [1]
Java Memory Model,JMM
Java
C/C++

Java Java

JDK 1.5 JSR-133 [2]


Java

12.3.1
Java
Variables Java
[3]

Java

Java Main Memory

Working Memory
[4]

[5]

12-2

2 Java Java

Java
[6]
12-2 12-1
[1] Java JDK 1.2 JDK 1.5

[2]JSR-133 Java Memory Model and Thread Specification Revision Java

[3] reference Java


reference Java
[4] “ ” “ 10MB
10MB ”

A
[5] Java volatile

volatile
[6] Java HotSpot Mark
Word GC GC Klass Point
8
12.3.2

Java 8
double
long load store read write
12.3.4 [1]

lock

unlock

read
load

load read

use

assign

store
write

write store

read load
store write Java
read load
store write a b
read a read b load b load a Java 8

read load store write

assign

assign
“ ”
load assign use store
assign load

lock lock
lock unlock

lock
load assign

lock unlock
unlock

unlock store write

8 volatile
Java
12.3.6
——

[1] JSR-133 8 Java


Java
12.3.3 volatile
volatile Java

synchronized volatile
volatile

Java volatile

volatile
“ ”

A B
A B

volatile “volatile
volatile
volatile volatile
” “ volatile
” volatile
volatile
Java
volatile
12-1

12-1 volatile

/**
*volatile
*
*@author zzm
*/
public class VolatileTest{
public static volatile int race=0
public static void increase {
race++
}
private static final int THREADS_COUNT=20
public static void main String[]args {
Thread[]threads=new Thread[THREADS_COUNT]
for int i=0 i THREADS_COUNT i++ {
threads[i]=new Thread new Runnable {
@Override
public void run {
for int i=0 i 10000 i++ {
increase
}
}
}
threads[i].start
}
//
while Thread.activeCount 1
Thread.yield
System.out.println race
}
}

20 race 10000
200000
200000
“race++” Javap
12-2 increase Class 4 return
race++
getstatic race volatile race
iconst_1 iadd race
putstatic race

12-2 VolatileTest

public static void increase


Code
Stack=2 Locals=0 Args_size=0
0 getstatic#13 //Field race I
3 iconst_1
4 iadd
5 putstatic#13 //Field race I
8 return
LineNumberTable
line 14 0
line 15 8

-XX +PrintAssembly

volatile
synchronized java.util.concurrent

12-3 volatile
shutdown doWork

12-3 volatile

volatile boolean shutdownRequested


public void shutdown {
shutdownRequested=true
}
public void doWork {
while shutdownRequested {
//do stuff
}
}

volatile

Java “ ” Within-Thread As-If-Serial


Semantics
12-4

12-4

Map configOptions
char[]configText
// volatile
volatile boolean initialized=false
// A
// initialized true
configOptions=new HashMap
configText=readConfigFile fileName
processConfigOptions configText,configOptions
initialized=true
// B
// initialized true A
while initialized {
sleep
}
// A
doSomethingWithConfig

12-4
initialized volatile
A “initialized=true”
Java
B
volatile [1]

volatile
12-5 DCL volatile volatile
JIT 4.2.7

12-5 DCL

public class Singleton{


private volatile static Singleton instance
public static Singleton getInstance {
if instance==null {
synchronized Singleton.class {
if instance==null {
instance=new Singleton
}
}
}
return instance
}
public static void main String[]args {
Singleton.getInstance
}

instance 12-6

12-6

0x01a3de0f mov$0x3375cdb0 %esi ……beb0cd75 33


{oop 'Singleton' }
0x01a3de14 mov%eax 0x150 %esi ……89865001 0000
0x01a3de1a shr$0x9 %esi ……c1ee09
0x01a3de1d movb$0x0 0x1104800 %esi ……c6860048 100100
0x01a3de24 lock addl$0x0 %esp ……f0830424 00
*putstatic instance
-
Singleton getInstance@24

volatile
mov%eax 0x150 %esi “lock addl 0x0 %esp ”
Memory Barrier Memory Fence
CPU
CPU
“addl 0x0 %esp ” ESP 0
nop IA32 lock nop
lock IA32 CPU Cache
CPU Invalidate Cache
Cache Java “store write” [2]

volatile CPU

CPU

CPU 1
A 10 2 A 2 3 B 3 1
2 —— A+10 *2 A*2+10 3
1 2 CPU A B
A B CPU lock
addl 0x0 %esp
“ ”

volatile volatile
—— volatile
synchronized java.util.concurrent
volatile synchronized
volatile volatile

volatile
volatile volatile

Java volatile T
V W volatile read load use assign
store write

T V load T V use
T V use T V
load T V use T V load read
V
V

T V assign T V store
T V store T V
assign T V assign T V store write
V
V
A T V use assign F A load
store P F V read write B
T W use assign G B load store
Q G W read write A B P Q
volatile

[1]volatile JDK 1.5 JDK


volatile volatile
JDK 1.5 Java DCL

[2]Doug Lea
http://g.oswego.edu/dl/jmm/cookbook.html
12.3.4 long double
Java lock unlock read load assign use store write 8
64 long double
volatile 64 32
64 load store read write 4
long double Nonatomic Treatment ofdouble and
long Variables

volatile long double

“ ”

“ ” Java
Java long double
“ ”
64
long double volatile
12.3.5
Java Java
3
3

Atomicity Java read load


assign use store write
long double

Java
lock unlock lock unlock
monitorenter monitorexit
Java ——synchronized synchronized

Visibility
volatile Java

volatile
volatile volatile
volatile

volatile Java synchronized final


“ unlock store
write ” final final
“this” this
“ ”
final 12-7 i j

12-7 final

public static final int i


public final int j
static{
i=0
//do something
}
{
//
j=0
//do something
}

Ordering Java volatile


Java

” Within-Thread As-If-Serial Semantics “ ”
“ ”
Java volatile synchronized volatile
synchronized “
lock ”

3 synchronized 3
“ ”
synchronized synchronized “ ”
“ ” 13
12.3.6
Java volatile synchronized
Java
Java “ ” happens-before

“ ” Java
A B B A
B “ ”

12-8 3

12-8 1

// A
i=1
// B
j=i
// C
i=2

A “i=1” B “j=i” B
j 1
“i=1” C “ ” A
i C A B
C A B C B j
1 2 C i B
B

Java “ ”

Program Order Rule

Monitor Lock Rule unlock lock


“ ”

volatile Volatile Variable Rule volatile


“ ”

Thread Start Rule Thread start

Thread Termination Rule


Thread.join Thread.isAlive

Thread Interruption Rule interrupt


Thread.interrupted

Finalizer Rule
finalize

Transitivity A B B C
A C

Java

“ ” “ ”
12-9

12-9 2

private int value=0


pubilc void setValue int value {
this.value=value
}
public int getValue {
return value
}

12-9 getter/setter A B
A “setValue 1 ” B
“getValue ” B

A B

lock unlock value volatile


volatile

A B B “getValue ”

getter/setter
synchronized value volatile
setter value value volatile
volatile

“ ”
“ ” “ ” “
” “ ”
12-10
12-10 3

//
int i=1
int j=2

12-10 “int i=1”


“int j=2” “int j=2”
12.4 Java
PHP Java
Java
Java Java

12.4.1

I/O
CPU

Java
start java.lang.Thread
Thread Java API
Native Java API Native
Native
“ ”
“Java ”

1.

Kernel-Level Thread,KLT Kernel


Scheduler

Multi-
Threads Kernel

——
Light Weight Process,LWP

1:1 12-3
12-3 1:1

User Mode Kernel


Mode

2.

User
Thread,UT

1 N 12-4
12-4 1 N

“ ” “

[1]
DOS
Java
Ruby

3.

N M 12-5

UNIX Solaris HP-UX N M


12-5 N M

4.Java

Java JDK 1.2 “ ” Green Threads


JDK 1.2 JDK
Java
Java
Java

Sun JDK Windows Linux


Java Windows Linux
[2]

Solaris Bound Threads


Alternate Libthread LWP/Thread Based Synchronization
Solaris JDK -XX
+UseLWPSynchronization -XX +UseBoundThreads

[1] “ ” “ ”

[2]Windows Fiber Package Linux NGPT 2.4


N M
12.4.2 Java

Cooperative Threads-Scheduling Preemptive Threads-


Scheduling

Lua “ ”

Windows 3.x
CPU

Java Thread.yield

Java
[1]
Windows 3.x Windows 9x/NT
“ ”

Java “ ”
——
Java 10 Thread.MIN_PRIORITY
Thread.MAX_PRIORITY Ready

Java

Java Solaris 2147483648 232

Windows 7 Java
Java 12-1
Java Windows Windows JDK
THREAD_PRIORITY_IDLE 6
“ ”

Windows “ ” Priority Boosting


“ ”

Ready

[1] JDK Coroutines


http://wikis.sun.com/display/mlvm/Coroutines
12.4.3
Java 5
5

New

Runable Runable Running Ready


CPU

Waiting CPU

● Timeout Object.wait

● Timeout Thread.join

●LockSupport.park

Timed Waiting CPU

●Thread.sleep

● Timeout Object.wait

● Timeout Thread.join

●LockSupport.parkNanos

●LockSupport.parkUntil

Blocked “ ” “ ” “ ”

Terminated

5 12-6
12-6
12.5
Java
Java
Java

“ ” “ ” 13
“ ”
13
Amdahl
“ ”

13.1

“ ”

“ ”
13.2
“ ”

Google “
” ——

Java Concurrency In Practice Brian Goetz “ ”


“ ” “ ”

13.2.1 Java
Java

“ ” [1]
Java
5

1.

Java JDK 1.5 Java Java


Immutable
12 final
this

“ ”

Java final

java.lang.String
substring replace concat
final 13-1
java.lang.Integer value final

13-1 JDK Integer

/**
*The value of the code Integer /code .
*@serial
*/
private final int value
/**
*Constructs a newly allocated code Integer /code object that
*represents the specified code int /code value.
*
*@param value the value to be represented by the
* code Integer /code object.
*/
public Integer int value {
this.value=value
}

Java API String


java.lang.Number Long Double BigInteger
BigDecimal Number AtomicInteger AtomicLong

2.

Brian Goetz
“ ”
Java API
Java API “ ”
“ ”

java.util.Vector Java
add get size synchronized

13-2

13-2 Vector

private static Vector Integer vector=new Vector Integer


public static void main String[]args {
while true {
for int i=0 i 10 i++ {
vector.add i
}
Thread removeThread=new Thread new Runnable {
@Override
public void run {
for int i=0 i vector.size i++ {
vector.remove i
}
}
}
Thread printThread=new Thread new Runnable {
@Override
public void run {
for int i=0 i vector.size i++ {
System.out.println vector.get i
}
}
}
removeThread.start
printThread.start
//
while Thread.activeCount 20
}
}
Exception in thread"Thread-132"java.lang.ArrayIndexOutOfBoundsException
Array index out of range 17
at java.util.Vector.remove Vector.java 777
at org.fenixsoft.mulithread.VectorTest$1.run VectorTest.java 21
at java.lang.Thread.run Thread.java 662

Vector get remove size

i
i ArrayIndexOutOfBoundsException
removeThread printThread 13-3

13-3 Vector

Thread removeThread=new Thread new Runnable {


@Override
public void run {
synchronized vector {
for int i=0 i vector.size i++ {
vector.remove i
}
}
}
}
Thread printThread=new Thread new Runnable {
@Override
public void run {
synchronized vector {
for int i=0 i vector.size i++ {
System.out.println vector.get i
}
}
}
}

3.

13-2
13-3

Java Vector HashTable


Collections synchronizedCollection

4.

Java API Vector


HashTable ArrayList HashMap

5.

Java
Thread suspend resume

suspend
resume
suspend resume JDK @Deprecated
System.setIn Sytem.setOut System.runFinalizersOnExit

[1] Brian Goetz IBM developWorkers


“ ”
13.2.2

1.

Mutual Exclusion Synchronization

Critical
Section Mutex Semaphore
4

Java synchronized synchronized


monitorenter monitorexit
reference Java
synchronized reference
synchronized Class

monitorenter
1
monitorexit 1 0

monitorenter monitorexit
synchronized
12 Java

synchronized getter setter


synchronized Java
Heavyweight

synchronized java.util.concurrent J.U.C


ReentrantLock ReentrantLock synchronized
API
lock unlock try/finally
synchronized,ReentrantLock 3
synchronized ReentrantLock

ReentrantLock Condition
synchronized wait notify notifyAll
ReentrantLock
newCondition

ReentrantLock
synchronized ReentrantLock Brian Goetz JDK 1.5
JDK 1.5 Xeon [1]
13-1
13-2

13-1 JDK 1.5

13-1 13-2 synchronized


ReentrantLock ReentrantLock
synchronized JDK 1.6
13.3 JDK 1.6
synchronized ReentrantLock
JDK 1.6 ReentrantLock
synchronized synchronized
synchronized
13-2 JDK 1.5 Xeon

2.

Blocking Synchronization

Non-Blocking Synchronization

“ ”

Test-and-Set

Fetch-and-Increment

Swap

Compare-and-Swap CAS

/ Load-Linked/Store-Conditional LL/SC

3 20
IA64 x86
cmpxchg CAS sparc-TSO casa ARM PowerPC
ldrex/strex LL/SC

CAS 3 Java
V A B CAS
V A B V
V V

JDK 1.5 Java CAS sun.misc.Unsafe


compareAndSwapInt compareAndSwapLong
CAS
[2]

Unsafe Unsafe.getUnsafe
Bootstrap ClassLoader Class
Java API J.U.C
compareAndSet getAndIncrement Unsafe CAS

12 CAS
12-1 20 10000
volatile “race++” increase
13-4

13-4 Atomic

/**
*Atomic
*
*@author zzm
*/
public class AtomicTest{
public static AtomicInteger race=new AtomicInteger 0
public static void increase {
race.incrementAndGet
}
private static final int THREADS_COUNT=20
public static void main String[]args throws Exception{
Thread[]threads=new Thread[THREADS_COUNT]
for int i=0 i THREADS_COUNT i++ {
threads[i]=new Thread new Runnable {
@Override
public void run {
for int i=0 i 10000 i++ {
increase
}
}
}
threads[i].start
}
while Thread.activeCount 1
Thread.yield
System.out.println race
}
}

200000

AtomicInteger int
incrementAndGet 13-5
13-5 incrementAndGet JDK

/**
*Atomically increment by one the current value.
*@return the updated value
*/
public final int incrementAndGet {
for {
int current=get
int next=current+1
if compareAndSet current,next
return next
}
}

incrementAndGet 1
“ - ”

CAS CAS
V A
A
B A CAS
CAS “ABA” J.U.C
“AtomicStampedReference”
CAS “ ” ABA
ABA

3.

Reentrant Code Pure Code

Thread Local Storage

“ -

Web “ ” Thread-per-Request
Web

Java volatile “
” Java C++ __declspec thread [3]

java.lang.ThreadLocal
Thread ThreadLocalMap
ThreadLocal.threadLocalHashCode K-V ThreadLocal
ThreadLocalMap ThreadLocal
threadLocalHashCode K-V

[1] Brian Goetz IBM developerWorks Java theory


and practice More flexible,scalable locking in JDK 5.0
http://www.ibm.com/developerworks/java/library/j-jtp10264/?S_TACT=105AGX52 S_CMP=cn-
a-j
[2] Intrinsics
Math.sin
[3] Visual C++ “__declspec thread ” GCC “__thread”
13.3
JDK 1.5 JDK 1.6 HotSpot
Adaptive Spinning
Lock Elimination Lock Coarsening Lightweight Locking
Biased Locking

13.3.1


JDK 1.4.2 -XX +UseSpinning


JDK 1.6

10
-XX PreBlockSpin

JDK 1.6

100

“ ”
13.3.2

11

Java
13-6 3

13-6

public String concatString String s1 String s2 String s3 {


return s1+s2+s3
}

String
String Javac String JDK 1.5
StringBuffer append JDK 1.5
StringBuilder append 13-6 13-7
[1]

13-7 Javac

public String concatString String s1 String s2 String s3 {


StringBuffer sb=new StringBuffer
sb.append s1
sb.append s2
sb.append s3
return sb.toString
}

StringBuffer.append
sb sb
concatString sb “ ” concatString

[1] JDK 1.5


StringBuilder
Java
13.3.3
——

13-7 append

13-7 append append


13.3.4
JDK 1.6 “ ”
“ ”

HotSpot
HotSpot Object Header
HashCode GC
Generational GC Age 32 64 32bit
64bit “Mark Word”

Mark Word
32 HotSpot
Mark Word 32bit 25bit HashCode 4bit
2bit 1bit 0
GC 13-1

“01”
Lock Record Mark
Word Displaced Displaced Mark Word
13-3

CAS Mark Word Lock Record


Mark Word
Mark Word 2bit “00”
13-4
13-3 CAS [1]

13-4 CAS

Mark Word

“10” Mark Word

CAS
Mark Word CAS Mark Word
Displaced Mark Word


” CAS
CAS

[1] 13-3 13-4 HotSpot Senior Staff Engineer——Paul Hohensee


PPT“The Hotspot Java Virtual Machine”
13.3.5
JDK 1.6
CAS
CAS

“ ” “ ” “ ”

Mark Word
-XX
+UseBiasedLocking JDK 1.6
“01” CAS
ID Mark Word CAS
Locking Unlocking
Mark Word Update

Revoke Bias “01”


“00”
Mark Word 13-5

13-5 Mark Word

Trade
Off
-XX -UseBiasedLocking
13.4
A Windows OpenJDK

C HotSpot

D OQL

E JDK
A Windows OpenJDK
A.1 JDK
JDK OpenJDK 6 OpenJDK 7
http://openjdk.java.net/ OpenJDK 6 OpenJDK 7
JDK 1.7 TCK 6 JDK 1.6
OpenJDK 7 “ ”

Mercurial Repository
Repository http://hg.openjdk.java.net/jdk7/jdk7
Release Note
Mercurial SVN ClearCase CVS
Source Releases
http://download.java.net/openjdk/jdk7/
OpenJDK 7 Early Access Source Build
b121 2010 12 9 81.7MB 308MB
A.2
Linux Solaris OpenJDK Windows
Linux Windows
README-builds.html OpenJDK

“Building the source code for the JDK requires a high level of technical
expertise.Sun provides the source code primarily for technical experts who want to conduct
research JDK Sun JDK

32 Windows 7 x86 OpenJDK 32


JDK x64 64
NTFS FAT32
512MB 600MB 512MB
600MB OpenJDK
600MB
C++ VS IDE
1GB

CYGWIN
Linux Windows
A.3
CYGWIN [1]
Windows Linux
Linux CYGWIN
GNU Make Makefile C/C++ Java
C++ ANT CYGWIN A-1
A-1

CYGWIN A-1
A-1 CYGWIN

JDK Java JDK Native


C++ C
Microsoft Visual Studio C++2003 VS2003 Microsoft Visual Studio
C++2010 VS2010
VS2010 Windows SDK v 7.0a
SDK PlatformSDK Visual Studio 2010 IDE
VS2010 Express C++
Visual Studio C++2010 Visual Studio C++2010 Express

CYGWIN VS2010 PATH


bin VS2010 bin CYGWIN bin
bin “link.exe” VS2010
OpenJDK

JDK JDK
——
JDK Hotspot JDK API JAXWS JAXP…… C++
Java Java JDK
JDK “Bootstrap JDK” OpenJDK 7 Bootstrap JDK JDK6
Update 14 JDK6 Update 21

Apache ANT,JDK Java ANT


ANT 1.6.5 Java

[1]CYGWIN http://www.cygwin.com/
A.4
OpenJDK 100%
OpenJDK
JDK “JDK Plug” [1]
Source Releases
Windows JDK Plug Jar

java-jar jdk-7-ea-plug-b121-windows-i586-09_dec_2010.jar

A-2 ACCEPT Plug


“ALT_BINARY_PLUGS_PATH” JDK
Plug

JDK Plug JDK JDK Java


HotSpot
“Optional Import JDK” Bootstrap JDK
“ALT_JDK_IMPORT_PATH” JDK

A-2 JDK Plug

2.3 FreeType [2]


JDK Swing
JConsole
“ALT_FREETYPE_LIB_PATH” “ALT_FREETYPE_HEADERS_PATH” FreeType
bin include
FreeType bin PATH

Microsoft DirectX 9.0 SDK Summer 2004 298MB


“ALT_DXSDK_PATH” DirectX 9.0 SDK

“MSVCR100.DLL”
Visual Studio 2010
744KB “ALT_MSVCRNN_DLL_PATH”
VS2003 “MSVCR73.DLL”
“Bootstrap JDK” bin

[1] 2011 JDK plug 2010 12 9


OpenJDK b121 JDK plug
[2]FreeType http://www.freetype.org/
A.5

VS2010 VCVARS32.BAT INCLUDE


LIB PATH
A-1
“ALT_COMPILER_PATH” Makefile

“ALT_BOOTDIR” “ALT_JDK_IMPORT_PATH”
JDK 1.6 “ANT_HOME” Apache ANT
A-1

A-1

SET ALT_BOOTDIR=D /_DevSpace/JDK 1.6.0_21


SET ALT_BINARY_PLUGS_PATH=D /jdkBuild/jdk7plug/openjdk-binary-plugs
SET ALT_JDK_IMPORT_PATH=D /_DevSpace/JDK 1.6.0_21
SET ANT_HOME=D /jdkBuild/apache-ant-1.7.0
SET ALT_MSVCRNN_DLL_PATH=D /jdkBuild/msvcr100
SET ALT_DXSDK_PATH=D /jdkBuild/msdxsdk
SET ALT_COMPILER_PATH=D /jdkBuild/vcpp2010.x86/bin
SET ALT_FREETYPE_HEADERS_PATH=D /jdkBuild/freetype-2.3.5-1-bin/include
SET ALT_FREETYPE_LIB_PATH=D /jdkBuild/freetype-2.3.5-1-bin/bin
SET INCLUDE=D /jdkBuild/vcpp2010.x86/include D /jdkBuild/vcpp2010.x86/sdk/Include %INCLUDE%
SET LIB=D /jdkBuild/vcpp2010.x86/lib D /jdkBuild/vcpp2010.x86/sdk/Lib %LIB%
SET LIBPATH=D /jdkBuild/vcpp2010.x86/lib %LIB%
SET PATH=D /jdkBuild/vcpp2010.x86/bin D /jdkBuild/vcpp2010.x86/dll/x86 D /Software/OpenSource/cygwin/bin %ALT_FREETYPE_LIB_PATH% %PATH%

JAVA_HOME

” -
“BUILD_CORBA” false CORBA
Java IDL idlj.exe *.idl CORBA

Cmd.exe
bash Bourne Again Shell sh
ksh JDK “jdk_generic_profile.sh” Shell
OpenJDK 7 B121 make sanity
A-2

A-2 make sanity

D \jdkBuild\openjdk7 bash
bash-3.2$make sanity
cygwin warning
MS-DOS style path detected C /Windows/system32/wscript.exe
Preferred POSIX equivalent is /cygdrive/c/Windows/system32/wscript.exe
CYGWIN environment variable option"nodosfilewarning"turns off this warning.
Consult the user's guide for more details about POSIX paths
http://cygwin.com/cygwin-ug-net/using.html#using-pathnames
cd./jdk/make \
…… ……
OpenJDK-specific settings
FREETYPE_HEADERS_PATH=D /jdkBuild/freetype-2.3.5-1-bin/include
ALT_FREETYPE_HEADERS_PATH=D /jdkBuild/freetype-2.3.5-1-bin/include
FREETYPE_LIB_PATH=D /jdkBuild/freetype-2.3.5-1-bin/bin
ALT_FREETYPE_LIB_PATH=D /jdkBuild/freetype-2.3.5-1-bin/bin
OPENJDK Import Binary Plug Settings
IMPORT_BINARY_PLUGS=true
BINARY_PLUGS_JARFILE=D /jdkBuild/jdk7plug/openjdk-binary-plugs/jre/lib/rt-closed.jar
ALT_BINARY_PLUGS_JARFILE=
BINARY_PLUGS_PATH=D /jdkBuild/jdk7plug/openjdk-binary-plugs
ALT_BINARY_PLUGS_PATH=D /jdkBuild/jdk7plug/openjdk-binary-plugs
BUILD_BINARY_PLUGS_PATH=J /re/jdk/1.7.0/promoted/latest/openjdk/binaryplugs
ALT_BUILD_BINARY_PLUGS_PATH=
PLUG_LIBRARY_NAMES=
Previous JDK Settings
PREVIOUS_RELEASE_PATH=USING-PREVIOUS_RELEASE_IMAGE
ALT_PREVIOUS_RELEASE_PATH=
PREVIOUS_JDK_VERSION=1.6.0
ALT_PREVIOUS_JDK_VERSION=
PREVIOUS_JDK_FILE=
ALT_PREVIOUS_JDK_FILE=
PREVIOUS_JRE_FILE=
ALT_PREVIOUS_JRE_FILE=
PREVIOUS_RELEASE_IMAGE=D /_DevSpace/JDK 1.6.0_21
ALT_PREVIOUS_RELEASE_IMAGE=
Sanity check passed.

Makefile Sanity “Sanity check


passed.” “make” Makefile Core i5/4GB
RAM JDK
“make clean”

OpenJDK build JDK


“java-version” JDK
B
C HotSpot
JDK 1.6 JDK 1.6 HotSpot Unstable
Options -XX JDK 1.6 660 -XX
+PrintFlagsFinal Diagnostic Experimental
-XX +UnlockDiagnosticVMOptions/-XX
+UnlockExperimentalVMOptions
3

-XX + option option

-XX - option option

-XX option = value option value

C.1
C.2
C.3
C.4
C.5
C.6
D OQL [1]

D.1 SELECT
SELECT
“*” SQL

SELECT * FROM java.lang.String

1.

SELECT toString s s.count,s.value FROM java.lang.String s

“@” Java MAT

SELECT toString s s.@usedHeapSize,s.@retainedHeapSize FROM java.lang.String s

“ ”

2.

AS

SELECT toString s AS Value


s.@usedHeapSize AS"Shallow Size"
s.@retainedHeapSize AS"Retained Size"
FROM java.lang.String s

“AS RETAINED SET”

SELECT AS RETAINED SET * FROM java.lang.String

3.

“OBJECTS” SELECT

SELECT OBJECTS dominators s FROM java.lang.String s

“dominators ”
“OBJECTS”
“OBJECTS” OQL
4.

“DISTINCT”

SELECT DISTINCT classof s FROM java.lang.String s

“classof ” Java
java.lang.String DISTINCT

java.lang.String

[1] Eclipse Memory Analyzer Tool MAT,Eclipse OQL


D.2 FROM
1.FROM

OQL FROM FROM

SELECT * FROM java.lang.String

SELECT * FROM"java\.lang\..*"

SELECT * FROM 0xe14a100

4 ID

SELECT * FROM 3022

SELECT * FROM SELECT * FROM java.lang.Class c WHERE c implements org.eclipse.mat.snapshot.model.IClass

“org.eclipse.mat.snapshot.model.IClass”
ISnapshot

SELECT * FROM $snapshot.getClasses

2.

“INSTANCEOF”

SELECT * FROM INSTANCEOF java.lang.ref.Reference

WeakReference SoftReference PhantomReference


java.lang.ref.Reference

SELECT * FROM $snapshot.getClassesByName "java.lang.ref.Reference" true


3.

FROM “OBJECTS” OQL

SELECT * FROM OBJECTS java.lang.String

java.lang.String Class
D.3 WHERE
1. = = [NOT]LIKE [NOT]IN

WHERE

SELECT * FROM java.lang.String s WHERE s.count =100


SELECT * FROM java.lang.String s WHERE toString s LIKE".*day"
SELECT * FROM java.lang.String s WHERE s.value NOT IN dominators s

2.= =

SELECT * FROM java.lang.String s WHERE toString s ="monday"

3.AND “ ”

SELECT * FROM java.lang.String s WHERE s.count 100 AND s.@retainedHeapSize s.@usedHeapSize

4.OR “ ”

“ ”

SELECT * FROM java.lang.String s WHERE s.count 1000 OR s.value.@length 1000

5.

null

SELECT * FROM java.lang.String s


WHERE s.count 1000 =true
WHERE toString s ="monday"
WHERE dominators s .size =0
WHERE s.@retainedHeapSize 1024L
WHERE s.@GCRootInfo =null
D.4
1.

“ ”

[ alias .] field . field . field ……

2. Java Bean

[ alias .]@ attribute ……

@ OQL Java Java

3. OQL Java

[ alias .]@ [ ] ……

“ ” MAT OQL Java


OQL Java
4.OQL

function parameter
D.5 OQL BNF
E JDK
JDK JDK 1.1.6 JDK
Oracle [1]
[1] http://www.oracle.com/technetwork/java/archive-139210.html

You might also like