Tuesday, May 17, 2011

Log memory utilization before and after a Java process run




Sometimes running a Java process requires ..
to calculate the amount of memory it needs/takes to run.

And sometimes logging the same is useful when the job grows in future.

Java API provides a mechanism to log the memory..
In such a way.., We can calculate memory available, used memory, total memory.. etc by using the API provided methods..

Method to get the Total memory available...

Runtime.getRuntime().totalMemory()

Similarly, we can get the available memory by...

Runtime.getRuntime().freeMemory()

and by doing some calculation, we get the memory used by a Process...

Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()

Combining all these data, conclude a method that will log the Total memory allocated and the memory used by the Process.


Now time to log the memory usage before and after a job/process run.

# Write a LogUtil class which has the below method.

Log memory utilization before and after a job run

/**
     * returns the total memory and used memory.
     *
     * @return total and used memory
     */
    public static String getMemoryUsageLog() {

        return MEMORY_ALLOCATED + "[" + String.valueOf(Runtime.getRuntime().totalMemory()) + "] " + MEMORY_USED + "[" +
                       String.valueOf(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) + "]";
    }


# Call the method from the Invoker class.

# Write a pre-execute method to call the Memory log util.

  /**
     * pre-execute method, initializes the pre-execute data
     *
     * @throws XXXRunException
     */
    protected void preExecute() throws XXXRunException {
        //memory usage before job run
        mLogger.debug("Memory Usage before Job Run : " + LogUtil.getMemoryUsageLog());       
    }

# Run the Process/Job

# Write a pre-execute method to call the Memory log util.

    /**
     * post-execute method, initializes the post-execute data
     *
     * @throws XXXRunException
     */
    protected void postExecute() throws XXXRunException {
        //memory usage after job run
        mLogger.debug("Memory Usage after Job Run : " + LogUtil.getMemoryUsageLog());       
    }

Now look for the memory logs in your loggers....! 

No comments:

Post a Comment