Understand the basic structure of the Java Virtual Machine JVM and the memory overflow mode of the JVM _java

Source: Internet
Author: User
Tags constant garbage collection static class throwable xms

Internal structure diagram of the JVM

Java virtual machines are mainly divided into five areas: Method area, Heap, Java stack, PC register, local method stack. Below
See some important questions about the structure of the JVM.

1. Which areas are shared? Which ones are private?

Java stacks, local method stacks, and program counters are created and destroyed with the start and end of user threads.
Each thread has a separate area of these. The method area and heap are shared by all threads in the entire JVM process.

2. What does the method area hold? Will it be recycled?

The method area is not just a saved method information and code, but also in a subregion called a running constant pool
The various symbolic references in the constants table in the class file are saved, as well as the direct references that are translated. Through the heap
A class object to access this information as an interface.

Although the method area holds type information, it is also recycled, except that the conditions for recycling are more stringent:

(1) All instances of the class have been reclaimed

(2) The ClassLoader that loaded the class has been recycled

(3) The class object is not referenced anywhere (including Class.forName reflection access)


3. Does the contents of a constant pool in the method area not change?

The Run-time constant pool in the method area holds data from the static constants pool in the class file. In addition to storing these compile-time
Generates a variety of literal and symbolic references, as well as direct references that are translated. But this does not mean that the running constant pool
Will not change. For example, the runtime can call the Intern method of string to put the new string constants into the pool.

Package COM.CDAI.JVM; 
 
public class Runtimeconstantpool {public 
 
  static void Main (string[] args) { 
 
    string S1 = new String ("Hello"); 
    String s2 = new string ("Hello"); 
    System.out.println ("before intern, S1 = = S2:" + (S1 = s2)); 
     
    S1 = S1.intern (); 
    S2 = S2.intern (); 
    System.out.println ("after intern, S1 = = S2:" + (S1 = s2)); 
     
  } 
 
 


4. Are all object instances allocated on the heap?

With the gradual maturation of escape analysis technology, stack allocation and scalar substitution optimization technology make "all objects are allocated
On the heap "also became less absolute.

The so-called escape is when a pointer to an object is referenced by multiple methods or threads, we call this pointer to escape.
In general, Java objects are allocated in heaps, and only pointers to objects are saved on the stack. Suppose a local variable
No escape occurs during method execution (outside of the method), then it is allocated directly on the stack, and then continues on the call stack
, the stack space is recycled and the local variables are recycled after the execution of the method. This reduces the amount of temporary
Objects are allocated in the heap, increasing the efficiency of GC recovery.

In addition, the escape analysis will be omitted from the local variable which does not occur, and the lock on the variable will be omitted.
Enable escape profiling by adding JVM startup parameters:-xx:+doescapeanalysis? Escapeanalysistest.


5. How many ways are there to access objects on the heap?

(1) Direct access to the pointer

The reference on the stack holds the pointer to the object on the heap, and the object can be positioned at once, and the access is faster.
But when the object is moved in the heap (the objects are often moved when garbage collection), the value of the pointer variable on the stack
Also need to change. This is the way the JVM hotspot is currently used.

(2) Handle indirect access

The reference on the stack points to a handle in the handle pool and accesses the object through the value in the handle. So handle
Like a level two pointer, it takes two times to locate the object, slower than the direct pointer location, but when
When an object moves in the heap, it does not need to change the value referenced on the stack.


how the JVM memory overflows
after learning about the role of the Java Virtual machine in five memory areas, let's continue to learn under what circumstances
Overflow occurs in these areas.

1. Virtual Machine parameter configuration

-XMS: Initial heap size, default to Physical memory 1/64 (<1GB), default (Minheapfreeratio parameters can be adjusted) when the free heap memory is less than 40%, the JVM increases the maximum limit of the heap up to-xmx.

-XMX: Maximum heap size, default (Maxheapfreeratio parameters can be adjusted) when the free heap memory is greater than 70%, the JVM reduces the heap until the-XMS minimum limit.

-XSS: The stack size of each thread. JDK5.0 the size of each thread stack is 1M, before each thread stack size is 256K. Appropriate adjustments should be made based on the memory size required for the applied thread. In the same physical memory, reducing this value can generate more threads. However, the operating system on a process of the number of threads is still limited, can not be unlimited generation, experience value in 3000~5000 around. Generally small applications, if the stack is not very deep, should be 128k sufficient, large application recommended 256k. This option has a higher performance impact and requires rigorous testing.

-xx:permsize: Sets the permanent generation (Perm Gen) initial value. The default value is 1/64 of the physical memory.

-xx:maxpermsize: Sets the maximum value for the persistent generation. 1/4 of the physical memory.


2. Method Area Overflow

Because the method area is to hold information about the class, it causes the method area to be loaded when we load too many classes
Overflow. Here we try to overflow the method area through both JDK dynamic proxy and Cglib proxy.

2.1 JDK Dynamic Proxy

Package com.cdai.jvm.overflow; 
Import Java.lang.reflect.InvocationHandler; 
Import Java.lang.reflect.Method; 
 
Import Java.lang.reflect.Proxy; public class Methodareaoverflow {static interface Oominterface {} static class Oomobject implements Oomin  Terface {} Static class OOMObject2 implements Oominterface {} public static void Main (string[] args) 
    {Final Oomobject object = new Oomobject (); while (true) {Oominterface proxy = (oominterface) proxy.newproxyinstance (Thread.CurrentThread (). Getcon Textclassloader (), OOMObject.class.getInterfaces (), new Invocationhandler () {@Overri 
              De public Object Invoke (Object Proxy, Method method, object[] args) throws Throwable { 
              System.out.println ("Interceptor1 is working"); 
            Return Method.invoke (object, args); 
      } 
          } 
      ); System.out.println (Proxy.getclass()); 
       
      System.out.println ("Proxy1:" + proxy);  
          Oominterface Proxy2 = (oominterface) proxy.newproxyinstance (Thread.CurrentThread (). Getcontextclassloader (), OOMObject.class.getInterfaces (), new Invocationhandler () {@Override publi C Object Invoke (Object proxy, Method method, object[] args) throws Throwable {System.out. 
              println ("Interceptor2 is working"); 
            Return Method.invoke (object, args); 
      } 
          } 
      ); 
      System.out.println (Proxy2.getclass ()); 
    System.out.println ("Proxy2:" + Proxy2); 
 } 
  } 
 
}

Although we continue to invoke the Proxy.newinstance () method to create the proxy class, the JVM does not have a memory overflow.
Each invocation generates a different instance of the proxy class, but the class object of the proxy class does not change. Is it a proxy?
Class has a cache on the proxy class object? The specific reason will be in the following "JDK dynamic agent and Cglib"
Detailed analysis.

2.2 Cglib Agent

Cglib also caches class objects for proxy classes, but we can configure them to not cache class objects.
This allows the method area to overflow by repeatedly creating the proxy class.

Package com.cdai.jvm.overflow; 
 
Import Java.lang.reflect.Method; 
 
Import Net.sf.cglib.proxy.Enhancer; 
Import Net.sf.cglib.proxy.MethodInterceptor; 
Import Net.sf.cglib.proxy.MethodProxy; 
 
public class MethodAreaOverflow2 { 
 
  static class Oomobject { 
  } public 
 
  static void Main (string[] args) { 
    wh Ile (True) { 
      enhancer enhancer = new enhancer (); 
      Enhancer.setsuperclass (oomobject.class); 
      Enhancer.setusecache (false); 
      Enhancer.setcallback (New Methodinterceptor () { 
        @Override public 
        object Intercept (Object obj. 
            object[] args, Methodproxy proxy) throws Throwable {return 
          method.invoke (obj, args); 
        } 
      }); 
      Oomobject proxy = (oomobject) enhancer.create (); 
      System.out.println (Proxy.getclass ());}} 
   
 


3. Heap Overflow

Heap overflow is relatively simple, simply by creating a large Array object to request a larger memory, you can make
Heap overflow occurred.

Package com.cdai.jvm.overflow; 
 
public class Heapoverflow { 
 
  private static final int MB = 1024 * 1024; 
   
  @SuppressWarnings ("unused") public 
  static void Main (string[] args) { 
    byte[] bigMemory = new byte[1024 * MB]; 
  } 
 
} 


4. Stack Overflow

Stack overflow is also more common, sometimes we write recursive calls do not have the correct termination conditions, the method will continue to
Recursion, the depth of the stack continues to increase, resulting in stack overflow.

Package com.cdai.jvm.overflow; 
 
public class StackOverflow { 
 
  private static int stackdepth = 1; 
   
  public static void StackOverflow () { 
    stackdepth++; 
    StackOverflow (); 
  } 
   
  public static void Main (string[] args) { 
    try { 
      stackoverflow (); 
    }  
    catch (Exception e) { 
      System.err.println ("Stack Depth:" + stackdepth); 
      E.printstacktrace ();}} 
   
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.