Wang Gang memory optimization performance optimization ---- (a) (java virtual machine in the data area of runtime garbage collection mechanism is how to determine the memory recovery, java four references, memory leaks)

First: memory optimization tool
memory optimization tools: DDMS MAT Finder-Activity, LeakCanary , LeakInspector and so on.
Second: java virtual machine data area at run time
1, run time data area has two things, one is the private area of threads, each thread will open up a thread to the private area; includes a program counter, stack virtual machine, local method stack. Another is a shared data area, all the threads can access, including the heap memory, the method comprising the constant region of the pool,
2, the program counter is an indicator of execution of the code, for determining the position of the next line of code is executed. For example, we write a method, this method has many lines of code, the program counter is to record the next line of the current code to perform memory address. After the completion of the current line of code is executed, the program guide us to the next line. If there are multiple threads running, each thread will have its own program counter. In the region is out of memory does not exist.
3, the virtual machine stack, store java method, we usually say that this area of the stack. The region appears oom and stackoverflow. Local variables, the method returns the address (after the end of the method call, the return address is returned to the stack) are stored in the area that there is a feature no memory fragmentation ( a contiguous storage space to store pictures, in the course of , there is a picture that we do not need, this picture has been deleted in memory. Then we store a message, but take up less memory space you want to delete our pictures, the next big storage memory than this when the information will be stored in this rearmost contiguous memory space, which would empty out part of the memory, this memory is called memory fragmentation, when we use a block of memory of a long time when this kind of memory broken The block abound) .
4, native method stacks will store some of the native method.
5, the heap memory and memory leaks easily occur out of memory, the contents of which mainly stores two kinds of information which, instances and arrays of objects (names saved to the stack array). This one is the biggest piece of virtual memory management functions, is the main battlefield of the GC.
6, the constant pool stores a number of literals (using public static final modified stuff), constants, String (char [] array storage type), the name of the class interface and method.
Here Insert Picture Description
That is, we can optimize the heap memory.
Third: garbage collection mechanism is how to determine the memory recovery
GC algorithm:
1, and reference counting algorithm
when we create an object of time, such as Object o1 = new Object () ;, which will do when there is a variable +1, i.e., 1 = count + 1; such a stack will have to go to a memory reference; then we write the following code.
O2 Object;
O2 = O1;
this time the counter will count + 1 + 1 = 2. There are two references cited heap. We write the following code;
o1 = null;
count is 1, i.e. 1 count = -1; this exposure time will be a problem, this time without a o1, O2 recovery counter, because the counter is also O1 1; count = 0 only when the recovery time will be. In this way we will create eight bytes of memory can not be recovered.
We do not apply this algorithm in the android;
2, reachability analysis algorithm, this algorithm is to use our android.
Here Insert Picture Description

GC ROOT can be used as an object, the virtual machine is running reference stack using static properties, constants, objects JNI references.
GC 2 is required scans only to be recovered, so we can finalize the object to save the loss of references
such as:

static App a;
@Override
protected void() throws Throwable{
	super.finalize();
	a=this;
}

Fourth, java four reference
phantom reference PhantomReference: survival not have any impact, recall notices for tracking the GC.
Weak references WeakReference: a first pass to, down to mark, the second scan to be recovered directly. It can also be used to track the GC recall notices

  @Test
    public void testWeakReference() throws InterruptedException {
        ReferenceQueue<Object> referenceQueuee=new ReferenceQueue<>();
        Object weakObject=new Object();
        //弱引用
        WeakReference weakReference=new WeakReference(weakObject,referenceQueuee);
        System.out.println("WeakReference:"+weakReference.get());//Object内存地址
        System.out.println("referenceQueuee:"+referenceQueuee.poll());//null

        weakObject=null;
        System.gc();
        Thread.sleep(2000);
        System.out.println("WeakReference:"+weakReference.get());//null
        System.out.println("referenceQueuee:"+referenceQueuee.poll());//object内存地址
    }



    @Test
    public void testPhantomReference() throws InterruptedException {
        //虚引用:功能,不会影响到对象的生命周期的,
        // 但是能让程序员知道该对象什么时候被 回收了
        ReferenceQueue<Object> referenceQueuee=new ReferenceQueue<>();
        Object phantomObject=new Object();
        PhantomReference phantomReference=new PhantomReference(phantomObject,referenceQueuee);
        phantomObject=null;
        System.out.println("phantomObject:"+phantomObject);//null
        System.out.println("phantomReference"+referenceQueuee.poll());//null
        System.gc();
        Thread.sleep(2000);
        System.out.println("referenceQueuee:"+referenceQueuee.poll());//地址
    }

Soft reference SoftReference: insufficient memory recall, store some importance is not very strong and can not easily make clear the object, such as the background picture does not need to immediately switch to show the
fifth: memory leaks
reason 1, a memory leak: the causes: a long life cycle of a short life cycle object holds references to objects
popular talk is the object of the recovery, as cited problem is not recycled, will eventually produce OOM
2, using the android profile of
selected run ---- profile app; it this tool can be opened
or select the button.
Here Insert Picture Description
After that we run this screen
Here Insert Picture Description
click on memory, select a section of memory. There are four fields Allocations Deallocations Total Count (number of instances of the heap), shallow size (this heap all instances of the total size, in bytes).
The most important thing is shallow size, to express our memory occupied by the object itself size.
Here Insert Picture Description

There is a format conversion tool D: \ hprof-conv.exe under the sdk \ platform-tools directory

3, optimizing a: Upon inquiry, we found that there are still switch to the background after MainActivity two places hold MainActivity references, leading to MainActivity can not be recovered. Two holding MainActivity reference is mServedView and mNextServedView. How to do it? We can reflect these two members in the Activity, and then dereference in onDestroy () in.

 @Override
    protected void onDestroy() {
        unRegisterBroadcastReceiver();
        super.onDestroy();
        method("mServedView");
        method("mNextServedView");
    }

    /**
     * 反射置空输入法中的属性
     * 传入的参数是一个属性,只要调用这个方法,就把这个属性置空。
     */
    public void method(String attr){
        //InputMethodManager:整个输入法框架(IMF)结构的核心API,应用程序之间进行调度和当前输入法交互。
        InputMethodManager im=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        //反射
        try{
            //拿到字段
            Field mCurRootViewField = InputMethodManager.class.getDeclaredField(attr);
            //不是public属性,设置权限
            mCurRootViewField.setAccessible(true);
            //取对象
            Object mCurRootView=mCurRootViewField.get(im);

            if (null!=mCurRootView) {
                Context context=((View)mCurRootView).getContext();
                if(context==this){
                    //破坏GC链
                    mCurRootViewField.set(im,null);
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

Guess you like

Origin blog.csdn.net/qczg_wxg/article/details/89786992