reprint: Http://www.jianshu.com/p/9fb0a795da931. Memory in Android 1.1 garbage collection mechanism in Android
The Android platform is one of the most attractive features for developers: There is a garbage collection mechanism that eliminates the need to manually manage memory, and the Android system automatically tracks all objects and frees objects that are no longer in use.
Young Generation Cenozoic
- Most new objects are located in the Eden (Eden) area
- When the Eden area is filled with objects, the minor GC is executed (lightweight GC). and transfer all surviving objects to one of the survivor areas.
- Survivor Space:s0, S1 has two, stores the object that survives after each garbage collection
The Minor GC also examines the surviving objects in the survivor area and transfers them to another survivor area, so that there will always be an empty survivor area for a period of time.
Old Generation Laosheng Generation
- Storing long-lived objects and surviving objects after multiple minor GC
Full major GC (heavier GC)
Permanent Generation Permanent Generation
Store the method area, in the method area, the class information to load, the static variables, the final type of constants, properties, and method information
1.2 Garbage collection
- Too much memory to allocate space for new objects
- Different virtual machines take different policies when GC occurs, and may halt execution of the current program
1.3 Garbage collection Mechanism &fps
- The Android system emits vsync signals every 16ms, triggering a rendering of the UI, so the entire process is guaranteed to reach a smooth image within 16ms. 60FPS
- If a frame's operation exceeds 16ms, it will make the user feel the Lag
- GC occurs during UI rendering, resulting in a frame drawing time exceeding 16ms
1.4 Memory leaks
During the entire Android development process, memory leaks are an important factor in the oom (out of memory overflow)
- The application allocates a large number of objects that cannot be reclaimed
- This leads to less memory being allocated
- When the creation of new objects requires insufficient memory
- A GC is called for garbage collection when the memory is found to be insufficient
- The result: There will be a lag
1.5 Memory Jitter
Cause: Memory jitter is due to the fact that the application creates a large number of objects in a short period of time and is released immediately.
- Generating a large number of objects in an instant can seriously occupy young generation's memory area
- When the threshold is reached and there is not enough space left, the GC is triggered and the newly created object is quickly recycled.
- Instant allocation of objects consumes very little memory, and a frequency-divided GC overlay increases the heap pressure
- Thus triggering more other types of GC.
- Result: This operation has the potential to affect the frame rate and make the user aware of performance issues
2. Memory Detection Tool 2.1 memory monitor
- Advantages
- Easy display of memory usage and GC conditions
- Whether the fast positioning of the stutter is related to GC
- Quickly locate crash crashes are associated with high memory consumption
- Quickly locate potential memory leak issues
- Simple to use
- Disadvantages
- Can't pinpoint the problem correctly
2.2 Allocation Tracker Assignment Tracker
- Advantages
- Locate the type, size, time, thread, stack, and other information of the assigned object in the code
- Locating memory jitter Issues
- Locating memory leaks with Heapviewer
- Disadvantages
- Display information for all objects (doughnut chart)
2.3 Heap Viewer Heap View
- Advantages
- Memory Snapshot Information
- Collect information once per GC
- Find a memory leak weapon
- Disadvantages
- Displays the allocated object size information (package view)
2.4 Leak Canary
Https://github.com/square/leakcanary
Reference
dependencies { ‘com.squareup.leakcanary:leakcanary-android:1.3‘ releaseCompile ‘com.squareup.leakcanary:leakcanary-android-no-op:1.3‘ }
Use
Memory Leak DetectionPrivate Refwatcher Refwatcher;PublicStatic RefwatcherGetrefwatcher (context context) {Ttapplication application = (ttapplication) context.getapplicationcontext (); return application.refwatcher;} @Override public void onCreate () {super.oncreate (), Refwatcher = Leakcanary.install (this); //detection} public void OnDestroy () {Refwatcher refwatcher = Ttapplication.getrefwatcher (Getactivity ()); Refwatcher.watch (this); //Memory leak detection}</code>
3. Common memory leak issues 3.1 single-case leaks
Save the context object in singleton mode, the instance object itself holds a reference to a context object, and the activity is immediately destroyed and cannot be recycled because the static variable holds its reference
public class AppManager {private static AppManager instance; private context context; private AppManager (context context" {this.context = Context;} public static AppManager getinstance (context Context) {if ( Instance! = null) {instance = new AppManager (context);} return instance; }}
can be changed to
PublicClassappmanager {private static AppManager instance; private context context; private AppManager (context context" {//Use Application context (can also be customized application) this.context = Context.getapplicationcontext (); } public static AppManager getinstance (context Context) {if ( Instance! = null) {instance = new AppManager (context);} return instance; }}
3.2 Leaks caused by static instances of non-static inner classes
Static Sresource will indirectly hold a reference to an mainactivity instance when it is created, causing mainactivity to not be recycled
PublicClassMainactivityextends activity {private static Span class= "Hljs-type" >testresource sresource = null; @Override protected void OnCreate ( bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (if (Sresource = null) {Sresource = new testresource (); //...} //non-static inner class class testresource {//...}}
Either set the inner class as a static inner class or extract the inner class to encapsulate it into a single case
Use Application context If you use the context
But dialog cannot use the context of application and service
3.3 Handler caused by memory leak problem
When an anonymous object is created, the object indirectly holds a reference to an instance of the external class, and the Mhandler object itself holds a reference to the mainactivity, causing the mainactivity to be destroyed immediately after destruction
PublicClassMainactivityextends Activity {private handler Mhandler = new handler () { @Override public void Handlemessage (message msg) {}}; @Override protected void OnCreate ( bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (private void LoadData () {//... request message Message = message.obtain (); Mhandler.sendmessage (Message);}}
Avoid using non-static inner classes in activity, such as declaring handler as static, so that handler's survival time is irrelevant to the activity.
Introduce the weak reference into the activity, avoid the activity as the context incoming
Empty before use
PublicClassMainactivityExtendsActivity {private staticClassMyHandlerExtendsHandler {PrivateFinalweakreference<Mainactivity> mactivity;private myhandler (MainActivity Activity) {mactivity = new weakreference< mainactivity> (activity);} @Override public void Handlemessage (message msg) {}} @Override protected void OnCreate ( Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); LoadData (); } private void LoadData () {//... request message Message = message.obtain (); Mhandler.sendmessage (Message);}}
3.4 Collection Class leaks
- If the collection class is a global variable (a static property in a class, a global map, such as an existing static reference, or final always points to it)
- No corresponding removal mechanism
- It is likely that the memory consumed by the collection will only increase
4. Ways to avoid memory leaks
- Try not to let static variables refer to activity
- Using WeakReference weak references guarantees that GC will be recycled
- Using static inner classes instead of inner classes, static inner classes do not hold references to external classes
- Static inner classes use weak references to reference external classes
- Releasing resources at the end of the declaration cycle
5. Reduce Memory usage
Use a lighter-weight data structure (Sparearray instead of HashMap)
- Google's own defined class takes up less memory
Avoid creating objects in the OnDraw method
- The OnDraw () method is frequently called, in which an object is created that causes too many temporary objects, and memory jitter occurs
Object Pool (Message.obtain ())
- When you must create an object in OnDraw, it is recommended that you use the object pool
- Equivalent to object buffering, when it is created, looks for objects that already exist, and does not create
LRUCache
- Significantly reduce memory usage
Bitmap memory multiplexing, compression (INSAMPLESIZE,INBITMAP)
StringBuilder
- Instead of string, especially when stitching
80.Android in-store management