深入理解Java虚拟机(第二版 带目录)
深入理解Java虚拟机(第二版 带目录)
——JVM
ISBN 978-7-111-42190-0
2013
+ 86-10-68995265
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
http://www.hzbook.com
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
“Java ” Sun
Sun Classic VM
Java Java
Java Sun
Java James Gosling Java
PDF Java 3
2005 7
Java Performance
2
http://hllvm.group.iteye.com/
JVM
High-Level Language Virtual Machine ITEye
Java RednaxelaFX http://rednaxelafx.iteye.com/
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
“
”
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
Java
Java
Class
Java API
Java
Java Java 4
J2EE
1-3 Java
1996 4 10 Java 9
8.3 Java 1996 5 Sun
JavaOne JavaOne 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
Java
[2]“HotRockit” http://hirt.se/presentations/WhatToExpect.ppt
1.4 Java
Java Java Java
Sun HotSpot BEA JRockit
IBM J9 JVM
Java
java version"1.2.2"
Classic VM build JDK-1.2.2-001 green threads,sunwjit
JIT C/C++
“Java ”
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
Java
Sun Java
1 KVM
KVM K “Kilobyte”
Android iOS
3 Squawk VM
Java C I/O
4 JavaInJava
5 Maxine VM
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
/ Java
1.4.6 Apache Harmony/Google Android Dalvik VM
Harmony VM Dalvik VM “ ” “Java ”
Java
Java
Android
Java ME Android Java
Sun
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]
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
API [1]
Java Java
JSR-292 Da Vinci Machine Nashorn
InvokeDynamic java.lang.invoke Java “Java ” “
”
[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
CPU
C CUDA Sumatra Java GPU Graphics
Processing Units APU Accelerated Processing Units
Java API Lambda JVM
[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
[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
1.6.1 JDK
OpenJDK Sun/OracleJDK OpenJDK 6 OpenJDK 7 OpenJDK
7u OpenJDK 8 JDK
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
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
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
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
#--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
-------------------------
./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]
make
env.sh
“JAVA_HOME
CLASSPATH HOTSPOT_BUILD_USER”3
“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
“ ” “ 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
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
n
gamma
“ ” env.sh
1-10
HotSpot
java.c main 1-11
HotSpot C/C++
1-3
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]
returnAddress
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 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
Java Java
“ ”
“ ”
Sun BUG BUG
HotSpot
Java
OutOfMemoryError
Java Class
Java
Class
[1]
Class Java
Class
String intern
OutOfMemoryError
[1] Class 6
2.2.7
Direct Memory Java
OutOfMemoryError
Java
RAM SWAP
-Xmx
OutOfMemoryError
2.3 HotSpot
Java
2.3.1
Java Java
new
Java Class
new
2.3.2
Java 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
//
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 markOop.cpp
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.1 Java
Java GC Roots
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
}
}
}
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
}
}
}
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
}
}
[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
}
}
}
OutOfMemoryError
“PermGen space” HotSpot
2-7 String.intern
Class
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{
}
}
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
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
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
}
}
3-1
Java GC Roots
JNI Native
3.2.3
“ ”
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
“ ”
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
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]
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
HotSpot OopMap “
” Safepoint
GC Safepoint
GC
“ ” ——
“
”
Safepoint
Sefepoint GC
JNI “ ”
Preemptive Suspension Voluntary Suspension
GC
“ ”
GC
GC
3-4
HotSpot
GC
GC HotSpot GC
3.5
Java
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
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
ParNew Serial
Server
Serial CMS JDK 1.5
HotSpot ——CMS
Concurrent Mark Sweep HotSpot
Concurrent
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
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
[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
Parallel Old “ ”
CPU Parallel Scavenge Parallel Old
Parallel Old 3-9
CMS remark
CMS
3-10 CMS
CMS
Sun Concurrent Low Pause
Collector CMS 3
CMS
i-CMS “deprecated”
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 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
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
Remembered Set G1
Initial Marking
Concurrent Marking
Final Marking
CMS G1 CMS
GC Roots
TAMS Next Top at Mark Start
Region GC Root
G1 G1
G1
“ ”
Java Microbenchmark Java -XX
+PrintGCDetails GC G1
Sun Garbage-First Garbage Collection
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
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]
“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
Minor GC Full GC
GC Minor GC Java
Minor GC
3-5 Minor GC
[1]JIT 11
3.6.2
Java
byte[]
Java
“ ” “ ”
“ ”
-XX PretenureSizeThreshold
Eden Survivor
3-6
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
3-7
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
[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
“ ”
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
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]
3-10 HotSpot
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]
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
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
jstat
jstat[option vmid[interval[s|ms][count]]]
interval count
250 2764 20
option 3
4-3
jstat
GlassFish v3
4-1
4-1 jstat
jstat
VisualVM
jstat
jinfo
jinfo[option]pid
CMSInitiatingOccupancyFraction
jmap
jmap[option]vmid
option 4-4
jhat dump
dump dump
[1]
jhat
VisualVM dump Eclipse Memory
Analyzer IBM HeapAnalyzer [2]
jhat 4-
3 jhat 4.2.4 jmap Eclipse IDE
jstack
jstack
jstack[option]vmid
option 4-5
4-4 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
4-6
-Xcomp “ ”
JIT [3]
-XX CompileCommand
sum sum -XX +PrintAssembly
4-7
4-7
2 push%ebp
3 sub$0x18 %esp
8 add$0x18 %esp
9 pop%ebp
11 ret
JDK
“ ”
1. 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
2 System.gc 4-6
System.gc
4-6 Eden
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
4-9 testLockThread
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
}
}
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
[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”
1.VisualVM
VisualVM NetBeans
VisualVM
jps jinfo
dump dump
Bug
plugins ……
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
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.
“CPU” “ ”
VisualVM CPU
“ ” 4-15
4-15 CPU
4.BTrace
BTrace [3]
“ ” VisualVM
HotSpot HotSwap [4]
VisualVM BTrace
“Trace Application……” BTrace
Java Java 4-16
4-16 BTrace
4-11 BTrace
4-12 BTrace
4-17 BTrace
BTrace
BTrace
JDK Sun
JDK HotSpot
HP HPjmeter [5]
HPjtune HP-UX SAP HotSpot 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
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
5-1 JBossCache
32 1.6GB
-XX +HeapDumpOnOutOfMemoryError
jstat GC
Eden Survivor “ ”
5-1
5-1
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
-Xss StackOverflowError
OutOfMemoryError unable to create new native thread
JNI JNI
GC GC
5.2.4
4 CPU Solaris 10
GlassFish
mpstat CPU CPU
CPU
Java
CPU
5-2
5-2 2
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
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
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
Java
5.3.1
Eclipse IDE
Klocwork ClearCase LT Eclipse
Eclipse “
”
-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
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
9115 4.114
JIT 1.999
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
JDK 3 5-4
5-4 JDK
TCK [4]
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 ”
-Dcom.sun.management.jmxremote
-Dosgi.requiredJavaVersion=1.5
-Xmx512m
-XX MaxPermSize=256M
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
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
Eclipse
-Xverify none
JDK JDK 1.6
JDK 1.5 5-8
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
VisualGC
Compile Time GC Time
JIT
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
Minor GC GC 1 378
VisualGC Eclipse 70
25 [1]
SafePoint GC
GC Eden
Survivor 35MB -Xmn
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
Eclipse Full GC
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
“Virtual”
[4]512MB 96MB
VMWare
5.3.5
Eclipse Eclipse
Eclipse
5-11 Eclipse
65 725
GC 65 GC 1
5-11
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
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
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
}
}
u2
constant_pool_count Java
1 0 6-3 0x00000008
0x0016 22 21 1 21
Class 0
“
” 0 Class
1
0
6-3
Descriptor
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
Class CONSTANT_Utf8_info
CONSTANT_Utf8_info Java
length u2 65535 Java
64KB
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]
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
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
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
6-1
“org/fenixsoft/clazz/TestClass” “.”
“/”
“ ”
inc m “inc” “m”
[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”
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-9
Override
Java Overload
[2]
Java
Class
Class
Class
Java
Class Java 2 9
Java Java SE 7
21 6-13
CONSTANT_Utf8_info
u4
6-14
1.Code
attribute_name_index CONSTANT_Utf8_info
“Code” attribute_length
6 6
Slot max_locals
Slot
Slot Javac Slot
max_locals
code_length u4
2 -1
32
65535
u2 Javac
Java
JSP JSP
JSP
2 B7 0xB7 invokespecial
reference private
u2
CONSTANT_Methodref_info
3 00 0A invokespecial 0x000A
“ init ”
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
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
LineNumberTable Java
Class Javac
-g none -g lines LineNumberTable
LineNumberTable 6-
18
4.LocalVariableTable
LocalVariableTable Java
Class Javac
-g none -g vars
IDE arg0
arg1
LocalVariableTable
6-19
local_variable_info 6-
20
start_pc length
index Slot 64
double long Slot index index+1
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_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 ”
attribute_length 0x00000000
9.StackMapTable
Sheng Liang
Java ME CLDC Class
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_index
CONSTANT_Utf8_info
Signature Signature
Signature
11.BootstrapMethods
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
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
Java
Java
Java
Java “Not Orthogonal”
6-31 Java
opcode T
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
ior lor
iand land
ixor lxor
iinc
Java Java
Java 3 4.2.2 4.2.4
Java
idiv ldiv
irem lrem ArithmeticException
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
float double
int long T N
N T
T T int long
IEEE 754
v v T int long v
v T
Java
6.4.5
Java
7
new
static static
getfield putfield getstatic putstatic
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
invokevirtual
Java
invokeinterface
invokespecial
invokestatic static
invokedynamic
4 Java invokedynamic
Java catch
jsr ret
6.4.10
Java
Monitor
ACC_SYNCHRONIZED
ACC_SYNCHRONIZED
6-6
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
Java 2 Class
ACC_SYNTHETIC ACC_ANNOTATION
ACC_ENUM ACC_BRIDGE ACC_VARARGS 5 JDK 1.5
JDK 1.7 12 Java
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
Class Java
“ ”
Class “Class
” “Class ”
7.2
7-1
7-1 5
Java
“ ” “ ” “ ”
Java
5 “ ”
2 java.lang.reflect
4 main
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
}
}
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
}
}
“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
Applet
java.lang.reflect.Proxy
ProxyGenerator.generateProxyClass “*$Proxy”
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
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
……
——
JDK 1.6 Javac Java Code
“StackMapTable”
Basic Block
StackMapTable
StackMapTable
Code StackMapTable
4.
——
……
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 “ ”
“ ” “ ”
ConstantValue value
ConstantValue value
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
[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
clinit init
clinit
clinit clinit
java.lang.Object
clinit
7-6 B 2 1
7-6 clinit
clinit
clinit
clinit clinit
clinit
clinit
clinit
clinit
clinit clinit
[2]
7-7
7-7
Thread[Thread-0 5 main]start
Thread[Thread-1 5 main]start
Thread[Thread-0 5 main]init DeadLoopClass
Java Java
Java Applet Java Applet “ ” [1]
OSGi Java
7.4.1
Java
Java
“ ”
Class
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
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
}
3
7-2
7-2
7-2 Parents
Delegation Model
Inheritance
Composition
Java
java.lang.Object
rt.jar
Object
Java
java.lang.ClassLoader loadClass 7-10
loadClass
ClassNotFoundException findClass
7-10
“ ” —— 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
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.*
4 Bundle ClassPath
“ ”
“ ”
OSGi
Java
OSGi OSGi
6 7 Class
8
Class
8
8.1
Java “ ” “ ”
Java
Facade Java
[1]
Java
Code [2]
Current Stack
Frame Current Method
8-1
8-1
8.2.1
Local Variable Table
Java Class Code max_locals
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
8-1 64MB
“-verbose gc”
System.gc 64MB
placeholder System.gc
placeholder placeholder
8-2
8-2 Slot
placeholder
System.gc placeholder
64MB
System.gc
“int a=0 ” 8-3
8-3 Slot
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
iadd
int int
iadd
int long float iadd
8-2
8-2
Java “ ” “ ”
8.2.3
[1]
8.3
[1] 2
8.2.4
Java athrow
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
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
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
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
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
}
}
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
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
}
}
“son.hardChoice new
QQ ” invokevirtual
hardChoice QQ
“QQ” “ QQ” “ QQ”
4.
“ ” “ ”
“ ”
Vritual Method Table vtable
invokeinterface ——Inteface Method Table itable
8-10
8-3
8-3
“ ”
Inline Cache “ ” Class
Hierarchy Analysis,CHA Guarded Inlining “ ”
11
1.
Java
Java Java JDK 1.7
[1]
“
/ ” “ ” Java
NegativeArraySizeException Java
NegativeArraySizeException
NoClassDefFoundError
Java
“
”
“ ”
“ ”
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
3.java.lang.invoke
MethodHandle
MethodHandle C/C++ Function Pointer C# Delegate
C/C++
Java
compare Comparator
Collections.sort
8-11 MethodHandle
getPrintlnMH invokevirtual
Class
MethodHandle “ ”
MethodHandle
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*”
8-12 invokedynamic
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
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
8-15 MethodHandle
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
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
[2]
32 80x86 8
32 ARM CPU PDA
16 32
[1] “ ”
Java
8-16
Java javap
8-17
8-17
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
Web ClassPath
Web “ ” ClassPath
“lib” “classes”
Java
Tomcat [1]
Tomcat
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 “ ”
Tomcat
“ ”
10 Web Spring
Spring Common Shared Spring
/WebApp/WEB-INF
CommonClassLoader SharedClassLoader Spring
7
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
9-2 OSGi
OSGi 9-2
OSGi
OSGi 9-2
java.*
Bundle Classpath
9-2 OSGi
—— 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
welcome
hello world
“ ” Proxy.newProxyInstance
IHello new Hello
sun.misc.ProxyGenerator.generateProxyClass
byte[]
main
“$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
}
}
}
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++
“ ”
JDK 1.5
Retrotranslator
Integer.valueOf Float.valueOf
[2]
JDK 1.7
invokedynamic
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
“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
9.3.1
“ ”
“ ”
“ ” “ ” “ ”
“ ”
5 250
Java
Java
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
}
}
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
JIT HotSpot VM C1 C2
3 Java
“ ” “ ”
“ ” Javac
JDK 1.3 Javac -O
[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]
10-3
Class Java 2
“Compiling for the Java Virtual Machine”
Java Class Class
JDK Javac
ECJ 10.3.1 Sun
Javac 3
3 10-4
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
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
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
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
“{}” “static{}”
clinit
clinit clinit
java.lang.Object init init
clinit
Gen.normalizeDefs
com.sun.tools.javac.jvm.ClassWriter writeClass
Class
10.3 Java
“
”
“ ” “ ”
“ ” “ ”
10.3.1
JDK 1.5 Parametersized Type
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
10-3
JDK Java
Java
Thinking in Java Bruce Eckel
[1]
JDK 1.5
C#
Java C#
Java
10-4
10-4 1
10-5
10-5 2
10-5
method Class 6
Class method_info
Class
Class
Java
JCP
Signature LocalVariableTypeTable
Signature
[3]
[4]
49.0
Class Signature
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
Java
10-6 10-7
10-6
10-7
10-6 5
10-7
Integer.valueOf
Integer.intValue
Iterable
10-8
10-8
10-8 6
6
“==” equals
Java
Java if 10-
9 if Java “ ”
“System.out.println "block 1" ” if
“System.out.println "block 2" ”
10-9 Java
Class
if
10-10
10-10
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
process Annotations
@SupportedAnnotationTypes @SupportedSourceVersion
“*”
Java
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
10-14
[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
Java Java
Java
Implementation Specific
HotSpot HotSpot
11.2 HotSpot
HotSpot
HotSpot
HotSpot
11.2.1
Java
HotSpot J9 [1]
“ ”
11-1
“-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
0 Profiling 1
1 C1
2 2 C2
[1] JRockit
“ ”
“ ”
“ ”
JIT
On
Stack Replacement OSR
“ ” “
” “ ” “ ”
“ ”
“ ”
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
Server
OSR
11-3
11-3
[1] “ ” Trace
FireFox TraceMonkey Dalvik JIT
[2]
11.2.3
OSR
-XX -BackgroundCompilation
JIT
High-
Level Intermediate Representaion,HIR HIR Static Single Assignment,SSA
HIR
HIR
HIR Low-Level
Intermediate Representation,LIR HIR
HIR
Client Compiler
Guarded Inlining Branch Frequency Prediction
Server Compiler
RISC Server Compiler
Client Compiler
Server
JIT
Java HotSpot
“ ”JIT
11.2.4
11-2
-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-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]
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
……
11-5
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
11-7 2
11-8 3
[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
11-8
Copy Propagation
“z” “y” “y” “z”
11-9
11-9
11-10
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
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
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
}
Autobox Elimination
Safepoint Elimination Dereflection
11.3.4
11-
12 testInline
11-12
“ ”
Java
Java
8 Java
invokespecial invokestatic
4 Java
final invokevirtual
Java Java
Java Java
Java
“ ”
final
Java
“ ” Class Hierarchy Analysis,CHA
CHA
CHA
Inline Cache
“
” “ ”
11.3.5
Escape Analysis Java
Synchronization Elimination
“ ” HotSpot
HotSpot
MicroBenchmarks
-XX +DoEscapeAnalysis
-XX +PrintEscapeAnalysis
-XX +EliminateAllocations
+XX +EliminateLocks -XX +PrintEliminateAllocations
Java C/C++
Java C/C++ C/C++ Java
API
“ ” “ ”
Java C/C++
Java
Java
Java
[2]
C/C++
C/C++
Java C/C++
C/C++ Alias Analysis Java Java
ClassA ClassB objA objB
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
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
12.3.1
Java
Variables Java
[3]
Java
Working Memory
[4]
[5]
12-2
2 Java Java
Java
[6]
12-2 12-1
[1] Java JDK 1.2 JDK 1.5
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
assign
assign
“ ”
load assign use store
assign load
lock lock
lock unlock
lock
load assign
lock unlock
unlock
8 volatile
Java
12.3.6
——
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
-XX +PrintAssembly
volatile
synchronized java.util.concurrent
12-3 volatile
shutdown doWork
12-3 volatile
volatile
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
instance 12-6
12-6
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
[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
“ ”
“ ” Java
Java long double
“ ”
64
long double volatile
12.3.5
Java Java
3
3
Java
lock unlock lock unlock
monitorenter monitorexit
Java ——synchronized synchronized
Visibility
volatile Java
volatile
volatile volatile
volatile
12-7 final
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 “ ”
Finalizer Rule
finalize
Transitivity A B B C
A C
Java
“ ” “ ”
12-9
12-9 2
12-9 getter/setter A B
A “setValue 1 ” B
“getValue ” B
A B
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.4.1
I/O
CPU
Java
start java.lang.Thread
Thread Java API
Native Java API Native
Native
“ ”
“Java ”
1.
Multi-
Threads Kernel
——
Light Weight Process,LWP
1:1 12-3
12-3 1:1
2.
User
Thread,UT
1 N 12-4
12-4 1 N
“ ” “
”
[1]
DOS
Java
Ruby
3.
N M 12-5
4.Java
[1] “ ” “ ”
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
Windows 7 Java
Java 12-1
Java Windows Windows JDK
THREAD_PRIORITY_IDLE 6
“ ”
Ready
New
Waiting CPU
● Timeout Object.wait
● Timeout Thread.join
●LockSupport.park
●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 “
” ——
“ ” “ ”
13.2.1 Java
Java
“ ” [1]
Java
5
1.
“ ”
Java final
java.lang.String
substring replace concat
final 13-1
java.lang.Integer value final
/**
*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
}
2.
Brian Goetz
“ ”
Java API
Java API “ ”
“ ”
java.util.Vector Java
add get size synchronized
13-2
13-2 Vector
i
i ArrayIndexOutOfBoundsException
removeThread printThread 13-3
13-3 Vector
3.
13-2
13-3
4.
5.
Java
Thread suspend resume
suspend
resume
suspend resume JDK @Deprecated
System.setIn Sytem.setOut System.runFinalizersOnExit
1.
Critical
Section Mutex Semaphore
4
monitorenter
1
monitorexit 1 0
monitorenter monitorexit
synchronized
12 Java
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
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
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.
“ -
”
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
13.3.1
“
”
10
-XX PreBlockSpin
JDK 1.6
100
“ ”
13.3.2
11
Java
13-6 3
13-6
String
String Javac String JDK 1.5
StringBuffer append JDK 1.5
StringBuilder append 13-6 13-7
[1]
13-7 Javac
StringBuffer.append
sb sb
concatString sb “ ” concatString
13-7 append
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
13-4 CAS
Mark Word
CAS
Mark Word CAS Mark Word
Displaced Mark Word
“
” CAS
CAS
“ ” “ ” “ ”
Mark Word
-XX
+UseBiasedLocking JDK 1.6
“01” CAS
ID Mark Word CAS
Locking Unlocking
Mark Word Update
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
”
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 JDK
——
JDK Hotspot JDK API JAXWS JAXP…… C++
Java Java JDK
JDK “Bootstrap JDK” OpenJDK 7 Bootstrap JDK JDK6
Update 14 JDK6 Update 21
[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
“MSVCR100.DLL”
Visual Studio 2010
744KB “ALT_MSVCRNN_DLL_PATH”
VS2003 “MSVCR73.DLL”
“Bootstrap JDK” bin
“ALT_BOOTDIR” “ALT_JDK_IMPORT_PATH”
JDK 1.6 “ANT_HOME” Apache ANT
A-1
A-1
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
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.
C.1
C.2
C.3
C.4
C.5
C.6
D OQL [1]
D.1 SELECT
SELECT
“*” SQL
1.
“ ”
2.
AS
3.
“OBJECTS” SELECT
“dominators ”
“OBJECTS”
“OBJECTS” OQL
4.
“DISTINCT”
“classof ” Java
java.lang.String DISTINCT
java.lang.String
SELECT * FROM"java\.lang\..*"
4 ID
“org.eclipse.mat.snapshot.model.IClass”
ISnapshot
2.
“INSTANCEOF”
java.lang.String Class
D.3 WHERE
1. = = [NOT]LIKE [NOT]IN
WHERE
2.= =
3.AND “ ”
4.OR “ ”
“ ”
5.
null
“ ”
2. Java Bean
3. OQL Java
[ alias .]@ [ ] ……
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