Question

I've been looking into memory management lately, and I create a Service like this:

public class MemoryManagerService extends Service {

    private boolean isRunning = true;
    private Thread memoryThread;

    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        Log.v("MemoryThread: ", "Created");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        memoryThread = new Thread(new MemoryManagerThread());
        memoryThread.start();
        Log.v("MemoryThread: ", "Started");
        isRunning = true;
        return START_STICKY;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        //memoryThread.stop();
        Log.v("MemoryThread: ", "Stopped");
        isRunning = false;
    }

    private class MemoryManagerThread implements Runnable
    {
        public MemoryManagerThread() {

        }

        @Override
        public void run() {

            while(isRunning) {
                try 
                {
                    Thread.sleep(5000);
                    Log.v("Allocated bytes", Long.toString(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()));
                }
                catch(Exception e) {}
            }
        }
    }
}

Which will only output the allocated memory each 5 seconds. This service is started from the my main activity. Of course the application will allocate memory, but what am worried about is the increasing memory.

I've seen in LogCat that every 5 seconds the allocated bytes increases by 80 bytes, which means 16 bytes/sec. Not very big numbers here, but it could be if the application is running "forever", or until the GC is starting. When the application starts it uses about 14 mb of memory. I should also mentioned that I've barely seen the GC_CONCURRENCE, which means that the GC is running due to low memory. Should I be worried regarding the memory in my app?

Was it helpful?

Solution

I would bet that if you only slept your thread for 3000 that you would gain 80 bytes every three seconds. Lots of little things allocate memory in your app, then it is available to be cleaned up at some (usually inopportune) point.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top