What is a memory leak
A memory leak, also known as a “memory leak,” is a memory location that is dynamically opened by a dynamic storage allocation function and is not released after use, resulting in the memory location being occupied. Until the end of the program. A memory leak is a memory leak. There are also many other arguments, such as: the heap memory that has been dynamically allocated in the program is not released or cannot be released for some reason, resulting in the waste of system memory, resulting in the program running speed slowing down, and even the serious consequences of system crash.
2. What can cause memory leakage and how to solve it
www.cnblogs.com/zjj1996/p/9…
Highlight: Due to the static nature of singletons, their lifetime is as long as the lifetime of the application. If an object is no longer needed but still holds a reference to that object, it cannot be recycled properly, resulting in a memory leak. Example: An example of preventing memory leaks from singletons
// Use singleton mode
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;
}
}
Copy the code
This way whatever Context is passed in will end up using the Application Context, and the singleton lifetime is as long as the Application’s, preventing memory leaks. ????? Memory leaks caused by the creation of static instances by non-static inner classes
For example, when an Activity is started frequently, to avoid creating the same data resource over and over again, it might look like this:
public class MainActivity extends AppCompatActivity {
private static TestResource mResource = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(mResource == null){
mResource = new TestResource();
}
//...
}
class TestResource {
//...
}
}
Copy the code
This creates a singleton of a non-static inner class inside the Activity, whose data is used each time the Activity is started. While this avoids duplication of resources, it can cause memory leaks. Because non-static inner classes hold references to external classes by default, the non-static inner class creates a static instance that has a lifetime as long as the application’s. As a result, the static instance will always hold references to the Activity, causing the Activity’s memory resources to fail to be recycled properly. Solution: Make the inner class static or extract it into a singleton, and use the Application Context if you need to use Context. 3. Memory leaks caused by handlers
Example: Creating a static object of an anonymous inner class
public class MainActivity extends AppCompatActivity {
private final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { // ... }}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new Thread(new Runnable() { @Override public void run() { // ... handler.sendEmptyMessage(0x123); }}); }Copy the code
}
When an Android application starts, the main thread of the application automatically creates a Looper object and a MessageQueue associated with it. When a Handler object is instantiated in the main thread, it is automatically associated with the main thread Looper’s MessageQueue. All Messags sent to MessageQueue hold a reference to Handler, so Looper calls Handle’s handleMessage() method accordingly to Handle the message. As long as there are unprocessed messages in the MessageQueue, Looper will continually fetch them and hand them to Handler. In addition, the Looper object for the main thread will accompany the entire life of the application. In Java, both non-static inner classes and anonymous inner classes potentially hold references to the external classes to which they belong, but static inner classes do not.
Looking at the example above, when MainActivity ends, the unprocessed message holds a reference to the handler, which in turn holds a reference to the external class to which it belongs, the MainActivity. This reference remains until the message is processed, preventing MainActivity from being collected by the garbage collector and causing a memory leak. Solution: Separate the Handler class or use a static inner class to avoid memory leaks. 4. Memory leaks caused by threads
Examples: AsyncTask and Runnable
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new Thread(new MyRunnable()).start(); new MyAsyncTask(this).execute(); } class MyAsyncTask extends AsyncTask<Void, Void, Void> { // ... public MyAsyncTask(Context context) { // ... } @Override protected Void doInBackground(Void... params) { // ... return null; } @Override protected void onPostExecute(Void aVoid) { // ... } } class MyRunnable implements Runnable { @Override public void run() { // ... }}}Copy the code
AsyncTask and Runnable both use anonymous inner classes, so they hold an implicit reference to their Activity. If the task is not completed before the Activity is destroyed, the Activity’s memory resources cannot be reclaimed, resulting in a memory leak. Solution: Separate AsyncTask and Runnable classes or use static inner classes to avoid memory leaks. 5. Memory leaks caused by unclosed resources
Resources that use BraodcastReceiver, ContentObserver, File, Cursor, Stream, Bitmap, etc., should be shut down or unregistered when the Activity is destroyed; otherwise, these resources will not be reclaimed, causing memory leaks.
1) For example, register a BraodcastReceiver in an Activity, but do not unregister the BraodcastReceiver after the Activity ends. 2) Resource objects such as Cursor, Stream, File, etc., usually use some buffer. When not in use, we should close them in time, so that their buffer can recycle the memory in time. Their buffering exists both inside and outside the Java Virtual machine. If we simply set its references to NULL without closing them, we tend to cause a memory leak. 3) When a resource object is not in use, call its close() function to close it, and then set it to NULL. Make sure our resource object is closed before our program exits. 4) Call recycle() to release memory when the Bitmap object is not in use. After 2.3, there is no need to manually recycle the memory in bitmap. The memory is already in the Java layer. Memory leaks caused by ListView usage
The ListView initially instantiates a number of View objects from the BaseAdapter based on the current screen layout, and the ListView caches these View objects. When you scroll up the ListView, the View object of the original top Item is reclaimed and used to construct the new Item that appears below. This construction is done by the getView() method, and the second parameter of getView(), convertView, is the cached View object of the Item (convertView is null if there is no View object in the cache at initialization).
When the Adapter was constructed, no cached convertView was used. Solution: Use the cached convertView when constructing the Adapter. Memory leak in collection container
We often add references to objects in a collection container (such as an ArrayList) without cleaning them out of the collection when we don’t need them, so the collection gets bigger and bigger. The situation is even worse if the collection is static. Solution: Before exiting the program, clear everything in the collection, set it to NULL, and exit the program. 8. WebView leaks
When we do not use a WebView object, we should call its destory() function to destroy it and free up its memory, otherwise it cannot be recycled for a long time, resulting in a memory leak. Solution: Open another process for WebView, communicate with the main thread through AIDL, and the process where WebView is located can choose the appropriate time to destroy according to business needs, so as to achieve the complete release of memory.
3. How to detect memory leaks
Memory leak refers to the failure of a program to free memory that is no longer used due to negligence or error. A memory leak does not mean that the BAI disappears physically, but that an application loses control of a certain segment of memory due to a design error, resulting in a waste of memory. You can use the appropriate software testing tools to test the software.
-
Ccmalloc – Simple memory leak and MALloc debugging library for C and C++ programs under Linux and Solaris.
-
Dmalloc – Debug Malloc Library.
-
Electric
A debugging library for Malloc () written by Bruce Perens in the fence-Linux distribution.
-
Leaky-linux a program that detects memory leaks.
-
Leaktracer-linux, Solaris, and hp-ux trace and analyze memory leaks in C++ programs.
-
MEMWATCH – by Johan
Written by Lindh, is an open source C language memory error detection tool, mainly through THE PRECessor of GCC.
- Valgrind-Debugging and profiling Linux programs, aiming at
programs written in C and C++.
- KCachegrind-A visualization tool for the profiling data
generated by Cachegrind and Calltree.
- Leak
Monitor- a Firefox extension that finds out the types of leaks associated with Firefox.
- IE Leak Detector
Drip/IE Sieve -Drip and IE Sieve Leak detectors help web developers improve dynamic web performance by reporting on memory leaks that are limited by Internet Explorer.
- Windows Leaks
Detector- Detects any resource leaks (memory, handles, etc.) in any Win32 application, calling hooks based on the Win API.
- SAP Memory
Analyzer- Is an open source JAVA memory analysis software that can be used to assist in finding memory leaks in JAVA programs. It can easily find large chunks of memory and verify who has been occupying it. It is based on the Eclipse RCP(Rich Client Platform). You can download standalone versions of RCP or plug-ins for Eclipse.
- DTrace- that is, Dynamic trace
Tracing is an open source software that can run on uniX-like platforms. Users can dynamically detect operating system kernel and user process to more accurately understand system resource usage, improve system performance, reduce support costs, and effectively adjust the system.
- IBM Rational PurifyPlus- Helps developers pinpoint C/C++, hosting. Performance and reliability errors in NET, Java, and VB6 code. PurifyPlus
Combine memory error and leak detection, application performance description, code coverage analysis, and more into a single, complete toolkit.
- Parasoft Sure+ +- Automatic runtime error detection for C/C++ applications. It automatically detects MEMORY corruption, memory leaks, pointer errors, and I/O errors in C/C++ applications. Through the use of a series of unique technologies (SCI technology and mutation testing, etc.), we thoroughly examine and test our code, pinpoint the exact location of errors and give detailed diagnostic information. Can be used as Microsoft
Visual C++ a plug-in to run.
- Compuware DevPartner for Visual C++ BoundsChecker
Suite- a runtime error detection and debugging tool for C++ developers. Runs as a plug-in for Microsoft Visual Studio and C++ 6.0.
- Electric Software GlowCode- Includes memory leak detection, code
Profiler, function call tracing, etc. Full error diagnosis and runtime performance analysis kit for C++ and.net developers.
- Compuware DevPartner Java
Edition- contains Java memory detection, code coverage testing, code performance testing, thread deadlocks, distributed applications and other major functional modules.
-
Quest JProbe- Analyzes Memory leaks in Java.
-
Ej-technologies JProfiler- a full-featured Java profiling tool dedicated to analyzing J2SE and J2EE applications. It combines CPU, thread, and memory profiling into one powerful application. JProfiler provides many IDE consolidation and application server consolidation uses. JProfiler’s intuitive GUI lets you find performance bottlenecks, catch memory leaks, and solve thread problems. 4.3.2 Registration Code: A-G666# 76114F-1OLM9Mv1i5UUly #0126
-
BEA JRockit- Used to diagnose Java memory leaks and identify root causes, optimized for the Intel platform for maximum performance on Intel hardware.
-
SciTech Software AB .NET Memory
Profiler- find memory leaks and optimize memory usage for C#, VB.Net, or others. Net program.
-
Yourkit.net & Java Profiler- industry leading Java and. NET program performance analysis tool.
-
AutomatedQA aqtime-automated qa’s award-winning products performance profiling and memory
Next generation replacement for the Debugging toolset, supporting Microsoft, Borland, Intel, Compaq and GNU compilers. Comprehensive and detailed reports can be generated for.NET and Windows applications to help you easily isolate and troubleshoot performance problems and memory/resource leaks in your code. Support for.NET 1.0,1.1,2.0,3.0 and Windows 32-bit / 64-bit applications.
- JavaScript Memory Leak Detector- Microsoft Global Product Development Europe team (Global Product)
Development- Europe Team (GPDE) publishes a debugging tool to detect memory leaks in JavaScript code, running as a plug-in for the IE family.
4. Java base data types and occupied bytes (plus)
Java basic data types
There are eight basic data types: byte, short, int, long, float, double, Boolean, char
Divided into four categories: integer, floating point, Boolean, character.
Integer types: byte, short, int, and long
Floating point: float, double
Boolean: Boolean
Character type: char
2. The size of bytes for each data type
The basic unit of a computer: the bit. A bit represents a 0 or a 1
Byte/Boolean: 1byte = 8 bits 1byte means 8 bits
Short/char: 2 byte
Int/float: 4 byte
Long/double: 8 byte
Three, each type of maximum storage data volume and data range
-
Byte Size Maximum amount of data to be stored Data rangeCopy the code
- Byte ——–1—- 8-bit ——2^8-1——- -2^ 8-2 ^8-1 byte
- Short — — — — — — — – 16-2 ^ 16 — 1 — — — — — — — 2 ^ 16 ~ 2 ^ 16-1
- Int — — — — — — — — – 4-32-2 ^ 32-1 – – – – – – – 2 ^ 32 ~ 2 ^ 32-1
- Long — — — — — — — — 8 — 64 — — — — — 2 ^ 64-1 – – – – – 2 ^ 64 ~ 2 ^ 64-1
- Boolean —–1—-8 bits —— (only one bit is used). The value can be true or false. Sometimes, the memory contains one bit
- Char — — — — — — — — 2-16 – store Unicode code, use single quotes assignment, said a single character
- Float — — — — — — – 4-32 – direct assignment must be combined with the number f f — — — — — — — 3.4 e-45 ~ 1.4 e38
- Double — — — — — – 8 — 64 — — — — — assignment can with d/d can also be without — — — — — — — e308 e-324 4.9 ~ 1.8
5, what is memory overflow and the solution
Memory overflow: (1) Avoid the above causes of memory overflow (2) check whether the pointer is NULL before using memory. Assume that the pointer p is an argument to the function, then use assert(p! =NULL) for checking. If (p==NULL) or if(p! =NULL) for error prevention. Memory leaks: (1) good coding habits, try to detect memory leaks in the program segment involving memory. (2) Overload new and delete. The allocated memory in the form of a linked list of their own management, after the completion of the use of the list removed from the linked list, the end of the program can be checked to change the linked list, which records the memory leak of the file (3) using intelligent Pointers. BoundsChecker, a common tool, locates errors that occur during program execution. (5) DEBUG and run the DEBUG version of the program, using the following technologies: CRT(C run-time libraries), runtime function call stack, memory allocation sequence number suggested when memory leak occurs (integrated development environment OUTPUT window), comprehensively analyze the cause of memory leak, and eliminate memory leak.
Check the following points: 1. Check whether all data is obtained in a database query. In general, if 100,000 records are fetched to memory at a time, memory may overflow. This problem is relatively hidden. Before going online, there is less data in the database, which is not easy to cause problems. After going online, there is more data in the database, and a query may cause memory overflow. So the database query as far as possible to use paging query. 2. Check your code for infinite loops or recursive calls. 3. Check whether a large loop repeatedly generates new object entities. 4. Check whether there is a query that obtains all data in the database. In general, if 100,000 records are fetched to memory at a time, memory may overflow. This problem is relatively hidden. Before going online, there is less data in the database, which is not easy to cause problems. After going online, there is more data in the database, and a query may cause memory overflow. So the database query as far as possible to use paging query. 5. Check whether collection objects, such as List and MAP, are uncleared after they are used up. Collection objects such as lists and maps always contain references to objects that cannot be collected by GC.
Dead notions about memory leaks
Memory Leak: refers to a program that fails to release or release dynamically allocated heap Memory for some reason, resulting in a waste of system Memory, slowing down the program and even crashing the system
“Out of memory” : when an application requests memory and does not have enough memory for the applicant. Or, if you are given a block of memory to store ints but you store longs, then you run out of memory and an OOM error is reported.
Memory optimization: 1. Solve memory leaks in service modules that occupy a large amount of memory. 2. Remove unwanted code and references from the program, using the default Lint detection with shrinkResources to remove invalid resources 3. Optimize the pictures to ensure that they are placed in a reasonable folder, load the appropriate picture size according to the View size, configure bitmap and recycle strategy 4 according to the mobile phone status. Optimize object creation, such as strings, use object pools, etc
2. What can cause memory leakage and how to solve it
If a collection has only methods to add elements and no corresponding deletion mechanism, the memory will be occupied later. If the collection is a global variable and there is no deletion mechanism, the memory usage of the collection will only increase.
2. Memory leaks Caused by singletons The lifetime of a single column static feature is as long as the lifetime of an application. If used improperly, memory leaks can occur.
3. Memory leaks caused by anonymous inner classes/non-static inner classes and asynchronous threads creating static instances of non-static inner classes
4. Anonymous internal class Android development will often inherit activities, fragment, view, if the use of anonymous class, asynchronous thread holding, no measures will be memory leaks.
Handler, Message, and messageQueue are all associated with each other. In case the message sent by Handler is not processed, Message and sent Handler objects are held by the thread Messagequeue. Handler is a TLS variable whose life cycle is inconsistent with view and activity.
6. Avoid static member variables. If your app process is designed to stay in memory, this memory will not be freed even if your app is cut to the background. According to the current mobile app memory management mechanism, background processes that occupy a large amount of memory will be recycled preferentially. Yi ‘wei If the APP has done process mutual protection, it will cause the app to restart frequently in the background. After the installation of the APP you participated in the development of the phone, the phone will be drained of power and traffic overnight, and your APP has to be uninstalled or silent by users.
7. Avoid Override Finalize ()
Resources that use BraodcastReceiver, ContentObserver, File, Cursor, Stream, Bitmap should be shut down or unregistered when the Activity is destroyed. Otherwise, these resources will not be reclaimed, causing a memory leak.
9. Memory stress caused by bad code