티스토리 뷰


아래 함수를 사용하면 자바 및 네이티브 힙의 크기 및 사용량을 체크할 수 있다.
DDMS에서 체크 가능한 Java Heap에는 문제가 없는데도 불구하고
OutOfMemoryError가 발생하면 이 함수를 이용해 Heap사용량을 먼저 체크하자.

// for check heap size
    public static void logHeap(Class clazz) {
     final int MEMORY_BUFFER_LIMIT_FOR_RESTART = 15;
        Double allocated = new Double(Debug.getNativeHeapAllocatedSize())/new Double((1048576));
        Double available = new Double(Debug.getNativeHeapSize())/new Double((1048576));
        Double free = new Double(Debug.getNativeHeapFreeSize())/new Double((1048576));
        DecimalFormat df = new DecimalFormat();
        df.setMaximumFractionDigits(2);
        df.setMinimumFractionDigits(2);
    
        Log.d(TAG, "debug. =================================");
        Log.d(TAG, "debug.heap native: allocated " + df.format(allocated) + "MB of " + df.format(available) + "MB (" + df.format(free) + "MB free) in [" + clazz.getName().replaceAll("com.asktingting.android.","") + "]");
        Log.d(TAG, "debug.memory: allocated: " + df.format(new Double(Runtime.getRuntime().totalMemory()/1048576)) + "MB of " + df.format(new Double(Runtime.getRuntime().maxMemory()/1048576))+ "MB (" + df.format(new Double(Runtime.getRuntime().freeMemory()/1048576)) +"MB free)");
        System.gc();
    
        // don't need to add the following lines, it's just an app specific handling in my app
        /*
        if (allocated>=(new Double(Runtime.getRuntime().maxMemory())/new Double((1048576))-MEMORY_BUFFER_LIMIT_FOR_RESTART)) {
            android.os.Process.killProcess(android.os.Process.myPid());
        }
        */
    }


댓글