诡异的内存泄漏


1.问题描述

当我们遇到下面的问题时,以为是创建了很多对象没有释放,或者数据库的cursor未关闭,导致了内存泄漏,但是等我们排查代码后,发现不是以上原因导致的

03-25 23:27:32.985 E/AndroidRuntime(12714): java.lang.OutOfMemoryError: Could not allocate JNI Env
03-25 23:27:32.985 E/AndroidRuntime(12714): at java.lang.Thread.nativeCreate(Native Method)
03-25 23:27:32.985 E/AndroidRuntime(12714): at java.lang.Thread.start(Thread.java:1063)

03-26 23:48:45.286 E/AndroidRuntime(31714): android.database.CursorWindowAllocationException: Cursor window allocation of 2048 kb failed.
03-26 23:48:45.286 E/AndroidRuntime(31714): at android.database.CursorWindow.(CursorWindow.java:108)
03-26 23:48:45.286 E/AndroidRuntime(31714): at android.database.AbstractWindowedCursor.clearOrCreateWindow(AbstractWindowedCursor.java:198)

java.lang.RuntimeException: Could not read input channel file descriptors from parcel.
at android.view.InputChannel.nativeReadFromParcel(Native Method)
at android.view.InputChannel.readFromParcel(InputChannel.java:148)
at android.view.InputChannel$1.createFromParcel(InputChannel.java:39)
at android.view.InputChannel$1.createFromParcel(InputChannel.java:37)

2.问题分析

再从log中仔细分析,我们会发现类似的信息"Too many open files"

E/art: ashmem_create_region failed for ‘indirect ref table’: Too many open files
E/Parcel (31714): dup() failed in Parcel::read, i is 0, fds[i] is -1, fd_count is 1, error: Too many open files

这个其实是我们的应用出现了文件句柄FD泄漏,不同线程打开了很多文件或者网络链接,没有及时断开,当超过系统限制时,则会导致错误,如果这时正好执行耗内存操作,则会出现该操作相关的OOM

3.问题复现

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private Button mLoginBtn;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mLoginBtn = findViewById(R.id.login);
        mLoginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        addMemory();
                    }
                }).start();
            }
        });
    }

    private void addMemory() {
        int count = 2000;
        for (int i = 0; i < count; i++) {
            //mStringBuilder.append(mTempStr);
            String filename = "temp"+i;
            File file = new File(getCacheDir(),filename);
            try{
                file.createNewFile();
                FileOutputStream out = new FileOutputStream(file);
            } catch (FileNotFoundException e){

            } catch (IOException e){

            }
        }
    }}

adb shell进入命令端
输入命令ps | grep myapplication,查找当前应用的进程号
输入命令cat proc/7589/limits | grep “open”,查看当前进程允许打开的文件总数
输入命令ls -la proc/7589/fd | wc -l,查看当前进程已打开的文件总数

当已打开的文件总数超过允许的总数时,我们的应用就会出错了

上一篇:linux进程后台运行及输出重定向


下一篇:移动端rem单位和px单位换算