Lifetime of an object, from creation to recovery

1. Description

java is a fully object-oriented programming language. For developers, object-oriented thinking is undoubtedly very important, but the object itself, we also need to know how objects come from? And how to die.

Usually we create an object of the most common ways are as follows

Object object=new Object();

This object is created, we can operate the object to achieve the features we need, but the problem is, how to create? After executing all the code, where the object went out?

2. How to create

Java learned all know, after the object is created, call the constructor and the initialization completion code blocks (here, without going into the execution order of the parent class subclass), this process is controlled, the process is fully operated programmer. But go deeper analysis of how objects are created yet.

  • Objects stored in any place

    The problem should first think about what is java virtual machine in place to store objects.

    java virtual machine memory will be managed in accordance with the following

    • Methods district

    • VM stack

    • Native method stacks

    • java heap

    • Program Counter

    If you do not consider escape analysis and distribution on the stack, java virtual machine will assign an object on the heap.

  • Open up much memory space

    Since it is an object to be stored, the natural need to open up a block of memory in the heap, then the question is, should open up much memory space for the object of it ?

    To make the problem easier, we usually want the object to allocate much memory before allocation is known, then our memory size is known it? The answer is yes, look at what classes, attributes and methods, properties from the basic data types and reference data types, data types share the memory is known, before allocating we know how much memory should be allocated.

  • What constitutes the object

    Object Memory consists of three parts: the object header, the object body alignment padding

    • Object header

      A first portion of its run-time data, such as hash code (HashCode), GC generational age lock state flag thread holds the lock, the thread ID bias, bias timestamp, a length of this part for storing data objects 32-bit and 64-bit virtual machine (not open compressed pointer), respectively, and for the 32bit 64bit, officially called "Mark Word".

      Mark Word is designed as a non-fixed data structures for storage in a very small space as much information, it will reuse their own storage space according to the state of the object.

      Another part of the object header pointer type, i.e., a pointer to its class object is metadata, the virtual machine is determined by the pointer which is an instance of the object class.

      If the object is a Java array, in that the object must have a head for recording the data length of the array.

    • Examples of data

      Examples of valid data portion is stored in the real target information, various types of program code in the field contents is defined.

    • Alignment padding

      Automatic memory management system requires the starting address of the object must be an integer multiple of 8 bytes, in other words, the size of the object must be an integer multiple of 8 bytes. The head portion and the object is exactly a multiple of 8 bytes (1 or 2 times), thus, when the object instance data portion is not aligned, it is necessary to completion by aligning padding.

  • How allocation

    • Pointer collision

      Assume that Java heap memory is absolutely regular, all memory is used aside, free memory on the other side, the middle stood a pointer as an indicator cut-off point, and that the allocated memory is just a pointer to that moving period equal to the size of the object from the side of the free space.

    • Free list

      If the Java heap memory is not regular, free memory and used memory intertwined, there is no way to simply be a pointer collision, the virtual machine must maintain a list of records on which memory block is available, to find a large enough space allocated to the object instance, and recorded on a list of updates from the list at the time of allocation, this allocation is called "free list" (free list).

    • Thread allocation buffer

      The above two methods appear to be no problem, but consider allocating objects multi-threaded environment, is likely to confuse free memory and used memory, how to solve this problem. Different threads to allocate memory for each thread is allocated a thread is allocated buffer (TLAB) java virtual machine when the thread is now allocated buffer allocation, so the buffer allocated for the thread, the only one thread to allocate memory above him, so will not be used and unused memory mixed up.

  • Why has the initial value of the object properties

    Already we have a block of memory used to store objects, but this memory may be used by someone else before too, in-memory data or previous data, then why a member variable of the object of our visit, even though we will have no initial initialize the value of it?

    When the memory allocation is completed, memory initialization jvm will be assigned a value of zero objects (not including the object header).

    So we have an object in the true sense, before we have analyzed, the object can be carried out in accordance with the requirements of programmers initialization method for initializing There are many construction methods, code blocks, direct initialization, etc., java virtual machine according to a certain these processes are sequentially packaged into a <init>method, after the call has been an object.

  • Small summary

    • Check the class is loaded into the method area, if not then perform class loading process
    • Allocating a fixed size memory block
    • The memory block initializes a value of zero
    • Execution <init>method

3. How to recycle

A feature of java is that programmers do not need to manually recover the object, but automatic garbage collection implemented by the java virtual machine.

Now we must make clear to recycle these issues?

  1. What objects need to be recovered
  2. How to recycle objects

How to recover objects rely on a specific garbage collector implementation, apparently in here know what objects need to recycle more important.

  • analysis

    What objects need to recover it? Think of what kind of stuff is garbage? The so-called junk refers to the use of this thing is no one, then it is rubbish, the object is the same, when an object is no place cited, this object is garbage, it should be recycled, and how useless it until this object? There are two general ways, but I will not speak here, but with our own ideas to analyze.

    public class Test{
        public static Object func1(){
            Object o1=new Object();
            return o1;
      }
        public static void func2(){
           Object o2=func1(); 
        }
        public static void main(String[] args){
            func2();
        }
    }

    We usually the object is achieved by assigning each reference cited transform the relationship to the above code as an example. Call func1 method func2 method, will first create an object, the object is accessed through o1. If you do not func2 method Object o2=func1(), o1 pointed objects can not be visited, but now due to be assigned to the 02 o1, o1 although no longer point to the object, but still had access to through o2, that is also the object with, it can not be recycled, when func2 method executed, because the main method reference that can not be saved before the object, causing the object could not be accessed, so the object can be recycled.

    So we can record each object how many references exist, when the reference number is 0, the object can then be recycled.

    But there is such a problem

    Class Test{
        Test t;
        public static Object func1(){
          Test t1,t2;
            t1.t=t2;
            t2.t=t1;
      }
        public static void main(String[] args){
          func1();
        }
    }

    func executed, it is clear that t1 and t2 should be recycled, but the references t1, t2 save, save a reference to t1 and t2, then their reference number is not zero.

    While above this algorithm is very simple to achieve, but because of the authority reference each other, so we can only think again.

    We will use a reference to an object on top of the place? Static class variables, constants and the like, when a local variable stack execution method.

    Since we will only use these types of places to perform a reference object, regardless of whether there is between objects refer to each other as long as they are not directly or indirectly referenced several of the above point, the object is to be recycled, so it seems those cited as root, as all the available objects bound to have one of these roots.

    In fact, two ideas above correspond to two different garbage collection algorithm

    • Reference counting
    • Reachability analysis
  • Reference counting

    For each object maintains a reference count, each time the object is a reference is added, it decreases a dereferenced, when the reference counter is 0, indicating that the object is not referenced, it can be recycled. The advantage of this method is simple, high efficiency, but the drawback is the problem can not be solved circular references.

  • Reachability analysis

    Reachability analysis algorithm, called the reference is to find the path traversed GC_Root called the chain of references, not in any object references a chain is unreachable, can be recycled, can be used as an object GC_Root include virtual machine stack the (local variable table) of the reference variable static method red region, constant region method.

Guess you like

Origin www.cnblogs.com/zeng-xian-hui/p/11240612.html