JVM summary

Chapter II: java memory area and memory overflow exception:

2.1 Memory map:

内存分布图
Heap and method area is shared by the threads;
virtual machine stack, native method stacks, the program counter is thread-private;
1. The thread counter : the number of lines used to specify the current thread of execution, bytecode. Multithreading is the JVM thread allocation alternately switched by the execution time to achieve, at any time, each thread in a processor will execute instructions, when the thread switching, in order to restore the thread when the correct position, so each thread must have a separate thread counter, so as to ensure threads do not affect each other.
2. Virtual machine stack : the life cycle of the threads are synchronized, each method performed at the same time, creates a stack frame for storing local variable table, the operand stack, dynamic links, and other information entrance method, each method invocation the completion of the execution process is a process to push the stack frame of the stack; local variable table storage RELATED local variables, including basic data, object reference and return address.
3. Native method stacks : basically the same virtual machine stack performs, generally confused, collectively stack, the only difference is the virtual machine stack is the implementation of a Java method, native method stacks is executing native method; local method is generally used in other languages (C , C ++, or assembly language, etc.) written and compiled based on native hardware and operating system programs,
4. Java heap : thread shared. All objects are allocated memory here, is the main area of garbage collection ( "GC heap"). Examples of main storage object. It can be expanded. Logically contiguous, are not necessarily physically consecutive
5. Method region (permanent area): Class information (fields, methods, interfaces) storing the virtual machine is loaded, a constant, static variables, like instant compiled code data; need not be physically continuous runtime constant pool area is part of the method, Class file constant pool (generated by the compiler of the literal and symbolic references, direct reference) will be placed in this area after class loading. In addition to the constant generated at compile time, but also allows the dynamic generation, e.g. intern String class (). Before jdk6.0, string constant pool has been the method area. After Jdk7.0, in a heap.
6. Direct Memory : not part of the virtual machine is running, you can directly access external heap memory; so when the dynamic memory can not be expanded when there will be an OutOfMemoryError; in JDK 1.4 introduces a new NIO class, it can use Native function library direct external memory heap allocation, and this is operated by referenced memory DirectByteBuffer heap as Java objects. This can significantly improve performance in some scenarios, it avoids memory to copy data back and forth outside the heap and stack.

2.2 Object Creation and abnormal

1. Create an object:
several ways: clone (clone without calling the constructor), new new keywords, deserialization (without calling the constructor), the reflection.
First new -> Check whether there is a symbol reference constant pool, and checks whether the symbol class is loaded, means too, not to perform the class load, and then begins to allocate memory.
Allocate memory: a pointer collision (java memory neat, finishing with compressed garbage collector Serial, ParNew), the free list (free memory intertwined, no compression finishing CMS).
Solve the synchronization problem objects created: 1 allocates memory space process synchronization processing (CAS accompanied by failure retry) 2. the memory space allocated on a different (native threads assigned buffer Tlab)

2.对象的内存布局:
1, 对象头:对象自身运行时的数据(哈希码,GC分代年龄,锁状态标志,)(类型指针:指向元数据的指针)
2, 实例数据:对象真正储存的有效信息(各种字段),
3, 对齐填充:占位符,补全字节。

3.对象的访问定位:
通过栈上的引用数据类型来操作堆上的具体对象
两种方式:

  1. 句柄:在对象被移动时(垃圾收集时会移动对象即内存整理),句柄只需修改句柄中的对象实例数据的指针,栈中的reference(引用)不需要修改。而直接指针需要修改。
  2. 直接指针:速度更快,因为少了一次指针定位的时间开销。

4.OutOfMemoryError异常:
1.java堆(heap)溢出:对象太多。注意概念:内存泄露:程序申请了内存空间,没有用,也无法释放。和内存溢出:没有足够的空间供其使用,
2.虚拟机栈和本地方法栈溢出:
1.请求的栈深度大于了允许的最大深度。 :StackOverflowError
2.扩展栈时无法申请到足够的内存空间。:OutOfMemoryError
3.方法和运行时常量池溢出:
4.本机直接内存溢出:

第三章:垃圾回收器与内存分配策略

1. Object recovery condition is determined:
1, reference counting algorithm: adding a counter to record. There is a reference to +1. References fail to -1 to 0 at any time he died. But we can not solve the problem of mutual loop references.
2. reachability analysis algorithm (mainstream): Select an object as a starting point. A chain is not subject to GC roots reach is unavailable. Select the starting point.
GC Roots selection: 1. Object subject object VM stack (local stack frame to scale) of zone 2. The method referenced class static attribute references cited 3. The method constant region 4. A native method stacks of native the method referenced object.
Four kinds of references:
1. strong references: objects are associated with strong references will not be recovered. Create a strong reference to a new object using a new way.
Object obj = new new Object ();
2. Soft Reference: soft reference object is associated will only be recovered in case of insufficient memory. Use SoftReference class to create soft references.
Object obj = new new Object ();
the SoftReference the SoftReference new new SF = (obj);
obj = null; // make objects are only associated with soft references
3. Weak references: weak reference associated with the object will be recovered, that is to say it only survive until the next garbage collection before they occur. Use WeakReference class to create a weak reference.
Object obj = new new Object ();
WeakReference new new WeakReference WF = (obj);
obj = null;
4. Phantom reference: also known as ghost or phantom references cited, whether an object has a virtual presence referenced, will not affect their survival time, you can not get a virtual objects by reference. Setting a virtual reference for the sole purpose of target system to receive a notification when the object is recovered. PhantomReference use to create a virtual reference.
Object obj = new new Object ();
the PhantomReference the PhantomReference new new PF = (obj, null);
obj = null;
recovery process zone (permanent generation): Waste constant (the constant point without any object in the pool) and useless class ( 1. all instances of the class have been recovered 2. load the class ClassLoader is recovered 3. class java.lang.Class object is not referenced in any place, not reflective access).

2.垃圾回收算法(重点):
1.标记-清除算法:效率不高,产生大量不连续的内存碎片
2.复制算法(新生代):分成一块大的Eden区和survivor区 。先使用Eden区和一块survivor区 回收时:存活的对象复制到另一块survivor区。然后清除,比例:8:1 不够就找老年代分配担保。
3.标记清理算法:标记-整理-清除。 所有存活的对象向一边移动,清掉边界外的。
4.分代收集算法:新生代:复制算法 老年代 :标记-清除或标记-整理
3.几种垃圾回收器:
单线程与多线程:单线程指的是垃圾收集器只使用一个线程,而多线程使用多个线程;
串行与并行:串行指的是垃圾收集器与用户程序交替执行,这意味着在执行垃圾收集的时候需要停顿用户程序;并行指的是垃圾收集器和用户程序同时执行。除了 CMS 和 G1 之外,其它垃圾收集器都是以串行的方式执行。
在这里插入图片描述
1.Serial: 最基本的,client模式下默认的新生代收集器
2.ParNew:Serial的多线程版,server模式首选的新生代收集器。只有前面这两个可以和CMS合用
3.Parallel Scavenge:新生代;复制算法。关注吞吐量。
4.Serial Old: Serial老年代版本:标记-整理,一般用于client,1,与Parallel Scavenge搭配 作为CMS的后备预案。
5.Parallel Old :Parallel Scavenge的老年代版本。 标记-整理
6.CMS:标记-清除。获取最短回收时间为目标。比较可以的。特点:对cpu资源敏感,
We can not handle floating garbage, a lot of space debris,
7.G1: cutting-edge technology. Features: Parallel and concurrent, generational collection, Spatial Integration, predictable pause,

4. memory allocation and recovery strategies:
Minor GC: the young generation space (including Eden and Survivor region) to reclaim memory
Major GC: clean up permanent generations.
Full GC: clean up the entire heap space - including the young generation and permanent generations. Conditions:
1. old's lack of space.
2. Generation eternal life (jkd7) or metadata space (jkd8) deficiency.
3.System.gc () method call.
4.CMS GC occurs when the promotion failed and concurrent mode failure
promoted to the old era when the average is greater than the remaining memory space 5.YoungGC years old
6. There is a continuous need to allocate large object
Stop-The-World: A Global suspended in Java phenomenon. Global pause, stop all Java code, Native code may be executed, but can not interact JVM
often involve moving of an object (such as replication between the object 1 in the above-mentioned and Survivor Survivor 0) in the garbage collection process, which led to the need for object references are updated. In order to ensure the correctness of the references updated, Java will be suspended all other threads, this is called "Stop-The-World", leading to a global system to a halt. Stop-The-World exists impact on system performance, the principle is to minimize the garbage collection "Stop-The-World" of time.
Memory allocation strategy:
1. Object priority assignment in Eden
2. Large Object (very long strings and arrays) directly into the old years
3. Long-term survival of the object (target age counter) years old will enter
4. Dynamic Object to determine the age of
5 space allocation guarantees

Chapter 7: VM class loading mechanism
1. class loading process.
Class in memory: loading , validation , preparation , parsing, initialization , use and uninstall . Determine the order of several bold. Resolve interspersed among them.
Loading time there is no clear beginning, but the initialization time is determined, there is one and only has to be

  1. Examples of new, read or class static field set, call the static method.
  2. java.lang.reflect. Reflecting the call.
  3. When a class is initialized, the first trigger initialization of the parent class.
  4. When starting Jvm, containing the main main class, initialized.
  5. What dynamic language that handles the corresponding class is not initialized,
    the following three will not:
  6. Reference a static field of the parent class by sub-category, sub-category does not cause initialization.
    System.out.println (SubClass.value); // value field defines the SuperClass
    2. The array definition referenced by the class, this class does not trigger initialization. This process will initialize the array type, an array type is generated automatically by a virtual machine, the subclass inherits directly from Object, which contains an array of properties and methods.
    SuperClass [] = new new SCA SuperClass [10];
    3. constants at compile time will be credited to the constant pool class is called, there is no direct reference to the definition of the class constants of nature, and therefore will not trigger initialization constants defined in the class.
    System.out.println (ConstClass.HELLOWORLD);

1. Load: 1> Get binary byte stream class defined by the fully qualified name of the class. 2> static storage structure represented by the byte stream data structure into the method area runtime 3> generates a class object, a method for accessing the various data entry areas of this class.
Obtaining binary stream:
1. Read from ZIP packages, become the basis JAR, EAR, WAR format.
2. Obtain from the network, the most typical application is the Applet.
3. calculates and generates run-time, such as dynamic agent technology, the use of proxy class ProxyGenerator.generateProxyClass binary stream of bytes java.lang.reflect.Proxy.
4. generated from other files, such as the corresponding Class class files generated by the JSP.

  1. Verify: File format validation, authentication metadata (information described bytecode semantic analysis), bytecode verification (the data flow and control flow analysis to ensure that the program is legitimate semantics, logical, class method will body check analysis), verification of symbolic references
  2. Preparation: class variables are modified static class variables and sets the initial value to allocate memory for the preparation phase, a method using a memory area. Instance variables will not allocate memory at this stage, it will be assigned when an object is instantiated along with the objects in the Java heap. The initial value is generally 0 values, for example, the following class variable value is initialized to 0 instead of 123. public static int value = 123; if the class variable is constant, it will be initialized according to the expression, 0 is assigned instead. public static final int value = 123;
  3. Analysis: The symbolic constant pool of reference for the process of replacing direct references. Mainly for the analysis operation: classes and interfaces, fields, methods class, interface method.
  4. Initialization: really began to execute java code class. Process virtual machines class constructor () method.
    () Is collected automatically by the compiler class assignment operation in all classes and static variables in the statement statement block merger of the order compiler appears collected by the statement in the source file is determined. Of particular note is the static statement block access to only define a class variable before it is defined in the class variables can only be assigned after it, can not be accessed. Static statements can not be used in the interface block, but there are still assignment class variables initialized and therefore generates different interfaces and classes () method. But different interfaces and classes that implements the interface () method does not need to run a parent interface () method. Only when the parent variables defined in the interface using parent interface will be initialized. Further, the interface implementation class will not be the same () interface method performed at initialization.
    Virtual opportunity to ensure a class () method is properly locked and synchronized in a multithreaded environment, if multiple threads to initialize a class at the same time, there will only be one thread execution of this class () method, other threads will be blocked waiting for, until active threads execute () method is completed. If there is a time-consuming operation in a class () method, it is possible to create multiple threads blocked, this blockage in the actual process is very subtle.

2. The class loader
1. It needs to be loaded by the class loader and the class itself establish its uniqueness in the Java virtual machine together.
Classification:
1. Start the class loader: implemented in C ++, is part of the virtual machine itself; \ bin jvm identified under
2. extension class loader: loading the \ bin \ ext directory, or a system variable path java.ext.dirs library under
3. the application class loader: the user class specified on the loading path (cLASSPATH) library

Parents delegation model : parent delegation model to organize the relationship between the three types of loader, it makes Java class as a class loader has the priority level together with a relationship of, so that the base class unified.
Work process: first, a class loader class loader forwards the request to the parent class loader only when the parent class loader can not complete attempt to load it.
Another escape analysis: dynamic scoping analysis of the object, if the thread can not access other methods or by any means to any object. This object can be optimized.
Three characteristics: the stack distribution, elimination of synchronization, scalar replacement.

第十二章,java内存模型和线程。
1.Java内存模型:定义程序中各个变量的访问规则
1.主内存(对应堆中的对象实例数据部分):所有的变量都存储在主内存中
2.工作内存(虚拟机栈部分,可以与前面将的处理器的高速缓存类比),线程的工作内存中保存了该线程使用到的变量到主内存副本拷贝,线程对变量的所有操作(读取、赋值)都必须在工作内存中进行,而不能直接读写主内存中的变量。不同线程之间无法直接访问对方工作内存中的变量,线程间变量值的传递均需要在主内存来完成
2.内存间的交互操作:
lock(锁定):作用于主内存的变量,把一个变量标识为一条线程独占状态。
unlock(解锁):作用于主内存变量,把一个处于锁定状态的变量释放出来,释放后的变量才可以被其他线程锁定。
read(读取):作用于主内存变量,把一个变量值从主内存传输到线程的工作内存中,以便随后的load动作使用
load(载入):作用于工作内存的变量,它把read操作从主内存中得到的变量值放入工作内存的变量副本中。
use(使用):作用于工作内存的变量,把工作内存中的一个变量值传递给执行引擎,每当虚拟机遇到一个需要使用变量的值的字节码指令时将会执行这个操作。
assign(赋值):作用于工作内存的变量,它把一个从执行引擎接收到的值赋值给工作内存的变量,每当虚拟机遇到一个给变量赋值的字节码指令时执行这个操作。
store(存储):作用于工作内存的变量,把工作内存中的一个变量的值传送到主内存中,以便随后的write的操作。
write(写入):作用于主内存的变量,它把store操作从工作内存中一个变量的值传送到主内存的变量中。
操作满足规则:
read和load store和write 必须顺序执行。不一定连续执行
• 不允许read和load、store和write操作之一单独出现
• 不允许一个线程丢弃它的最近assign的操作,即变量在工作内存中改变了之后必须同步到主内存中。
• 不允许一个线程无原因地(没有发生过任何assign操作)把数据从工作内存同步回主内存中。
• 一个新的变量只能在主内存中诞生,不允许在工作内存中直接使用一个未被初始化(load或assign)的变量。即就是对一个变量实施use和store操作之前,必须先执行过了assign和load操作。
• 一个变量在同一时刻只允许一条线程对其进行lock操作,lock和unlock必须成对出现
• 如果对一个变量执行lock操作,将会清空工作内存中此变量的值,在执行引擎使用这个变量前需要重新执行load或assign操作初始化变量的值
• 如果一个变量事先没有被lock操作锁定,则不允许对它执行unlock操作;也不允许去unlock一个被其他线程锁定的变量。
• 对一个变量执行unlock操作之前,必须先把此变量同步到主内存中(执行store和write操作)。
Volatile的特殊性:稍弱的同步机制,可见性,禁止指令重排序。没有保证原子性。
Long和double的特殊规则:8字节。读写允许划分两个步骤。很少出现。
Atomicity (locks, atomic class): a operation is not interrupted, either all succeed or perform all failed, with the feeling of "live and die" in.
Visibility (volatile, synchronized, final): When a thread modifies shared variables, other threads can be aware of this change immediately.
Orderliness (volatile, synchronized): If viewed in this thread, all operations are ordered; observed if another thread in a thread, all operations are disordered.
First principle occurs first; the program sequence rules, rules pipe lock, volatile variable rules, rule thread starts, the thread terminates rules, break the rules of the thread, the object end rule, transitive
state of transformation:
在这里插入图片描述the thread package includes the following five states.

  1. New state (New): After the thread object is created, entered the new state. For example, Thread thread = new Thread ().
  2. Ready state (Runnable): also known as "executable state." After the thread object is created, other thread calls the start () method of the object, so as to start the thread. For example, thread.start (). Thread a state of readiness at any time may be executed by the CPU scheduling.
  3. Running state (Running): CPU thread to obtain permission for execution. Note that, the thread can only be entered from the ready state to the running state.
  4. 阻塞状态(Blocked) : 阻塞状态是线程因为某种原因放弃CPU使用权,暂时停止运行。直到线程进入就绪状态,才有机会转到运行状态。阻塞的情况分三种:
    (01) 等待阻塞 – 通过调用线程的wait()方法,让线程等待某工作的完成。
    (02) 同步阻塞 – 线程在获取synchronized同步锁失败(因为锁被其它线程所占用),它会进入同步阻塞状态。
    (03) 其他阻塞 – 通过调用线程的sleep()或join()或发出了I/O请求时,线程会进入到阻塞状态。当sleep()状态超时、join()等待线程终止或者超时、或者I/O处理完毕时,线程重新转入就绪状态。
  5. 死亡状态(Dead) : 线程执行完了或者因异常退出了run()方法,该线程结束生命周期。

第十三章:线程安全和锁优化
线程安全的等级:
1. 不可变:final 修饰 string等不可变类。绝对线程安全。
2. 绝对线程安全:基本没有绝对的。
3. 相对线程安全:这就是我们一般说的线程安全。如:vector等。
4. 线程兼容;arraylist等,
5. 线程对立:无法在多线程中使用,
线程安全的实现方法:
1. 互斥同步(阻塞式同步)

  1. 同步指的是:多个线程并发访问共享数据时,保证共享数据在同一时刻只能被一个线程使用。
  2. 互斥指的是:同步的手段。如:临界区、互斥量和信号量。
  3. 最基本的同步互斥手段:synchronized关键字。
    a) 原理:synchronized关键字经过编译后,会在同步代码块前后分别形成monitorenter和monitorexit这两个字节码指令。
    b) 在执行monitorenter指令时,首先要尝试获取对象锁。若这个对象没被设定锁,或已经拥有了这个对象锁,把锁的计数器+1。
    c) 相应的执行monitorexit指令时,锁计数器-1,当为0时释放锁。
    d) 若获得对象失败则阻塞当前线程。
  4. 另一种手段:ReentrantLock来实现
    reentrantLock增加的新功能:
    a) 等待可中断:当持有锁的线程长期不释放锁的时候,正在等待的线程可以选择放弃等待。
    b) 公平锁:可以讲多个线程在等待同一个锁时,必须按照申请锁的时间顺序依次获得锁。
    c) 锁绑定多个条件:一个ReentranLock对象可以同时绑定多个Condition对象。
  5. 两种方式的比较:
    a) 在JDK1.6之前在多线程环境中synchronized的吞吐量下降的严重,但ReentranLock性能几乎不变。
    b) 在JDK1.6之后二者性能基本上持平。
    c) 应该优先考虑使用synchronized来同步。
    2. 非阻塞同步
    1,互斥同步属于一种悲观的并发策略。即总认为不去做同步措施就一定会出现问题,故无论共享数据是否真的会出现竞争,都要加锁。
    2,非线程阻塞:是基于冲突检测的乐观并发控制策略。即先操作,如果没有其它线程征用共享数据,则成功。如果共享数据有征用,采取补偿措施。(不断的重试,直到成功)
    3. 无同步方案
    如果方法中不涉及共享数据,那它自然无须任何同步措施去保证正确性。
    1)可重入代码
    可重入的代码都是线程安全的,但并非所有的线程安全的代码都是可重入的。
    2)线程本地保存

锁优化:
锁优化技术:适应性自旋、锁消除、锁粗化、轻量级锁和偏向锁。
1.适应性自旋
1.自旋锁:当两个或两个以上的线程同时并行执行,让后面请求锁的那个线程“稍等一下”,但不放弃处理器的执行时间,看看持有所的线程是否能很快释放锁。
2.缺点:自旋的线程只会白白消耗处理器资源,带来性能的浪费。故需要使等待时间有一定的限度
3.改进:等待时间要自适应。等待时间随着程序运行和性能监控信息的不断完善。

2.锁消除
1.锁消除:虚拟机及时编译器在运行时,对一些代码上要求同步,但是被检测到不可能存在共享数据竞争的锁进行消除。
2.判断依据:源于逃逸分析的数据支持。若堆上的所有数据都不会逃逸出去从而被其他线程访问到,那就可以吧它们当作栈上的数据看待。
3.粗粒化
1.上面出现的问题:如果一系列的连续操作都对同一个对象反复加锁和解锁,甚至加锁操作是出现在循环体中,那即使没有线程竞争,频繁地进行互斥同步操作也会导致不必要的性能损耗。
2.措施:如果虚拟机探测到有这样一串零碎的操作都对同一个对象加锁,【将会把加锁同步的范围扩展到整个操作序列外部】。
4.轻量级锁
1.加锁过程:
1)代码进入到同步代码块的时候,如果此同步对象没有被锁定,将会在当前线程的栈帧中建立一个名为锁记录(Lock Record)空间,用来存储对象目前的头数据。
2)将对象的头记录更新为指向Lock Record的指针。
a)更新成功:那么这个线程就拥有了该对象的锁
b)失败:检查对象的对象头是否指向当前线程的栈帧。
a)是:说明当前线程已经拥有这个对象的锁,直接进入同步块中执行。
b)否:说明这个锁对象已经被其他线程抢占。
3)如果两条以上线程征用同一个锁,那轻量级锁失效。
2.解锁过程:
1)若对象的对象头仍然指向现成的锁记录,则把对象当前的Mark Word和线程中副本替换回来。
A)成功:整个同步过程完成
b)失败:说明其他线程尝试获取该锁,那就要释放锁的同时唤醒被挂起的线程。
5.偏向锁
1.与轻量级锁的区别:
轻量级锁:是在无竞争情况下,消除同步使用的互斥量。
偏向锁:在无竞争情况下把整个同步都消除掉。
2.加锁过程:
1)当锁对象第一次被线程获取的时候,虚拟机包对象头中的标记为设为“01”。
2)获取到这个锁的线程的ID记录在对象的Mark Word之中。
a)成功:持有偏向锁的线程以后每次进入这个锁相关的同步块时,可不再进行任何同步操作。
3.解锁过程:
1)当有另外一个线程去尝试获取这个锁时,偏向模式宣告结束。
2)根据锁对象目前是否处于被锁定的状态,撤销偏向后恢复到“01”或“00”。
4.优点:提高带有同步但竞争的程序性能。

Guess you like

Origin blog.csdn.net/qq_41703795/article/details/89280905