views:

630

answers:

4

Hi, I am running JBOSS server by deploying my own classes.Now i started doing some operations on my application.Now i would like to know the memory used by my application before and after performing operations.please support me in this regard

+1  A: 

Runtime.getRuntime().freeMemory() returns what you want. Have a look at the docs.

Allain Lalonde
+1  A: 

Get the free memory before doing the operation Runtime.getRuntime().freeMemory() and then again after finishing the operation and you will get the memory used by your operation.

Bhushan
not if another thread did much of anything between the two calls to freeMemory()....thus is the problem with such things.... Heisenberg was a pretty smart guy :)
Jared
+4  A: 

By using MemoryMXBean (retrieved by calling ManagementFactory.getMemoryMXBean()) as well as Runtime.getRuntime()'s methods .totalMemory(), .maxMemory() and .freeMemory()

Note that this is not an exact art: while creating a new object, other temporary ones may be allocated, which will not give you an accurate measurement. As we know, java garbage collection is not guaranteed so you can't necessarily do that to eliminate dead objects.

If you research, you'll see that most code that attempts to do these measurements will have loops of Runtime.gc() calls and sleeps etc to try and ensure that the measurement is accurate. And this will only work on certain JVM implementations...

On an app server/deployed application, you will likely only get gross measurements/usage changes as the heap is allocated and the gc fires, but it should be enough. [I'm presuming that you wouldn't implement gc()'s and sleeps in production code :)]

Stephen
A: 

You may find the results you get are inconclusive. The GC will clean up used memory at random points in the background so you might find at if you run the same operations many times you will get different results. You can even appear to have more memory free after performing an operation.

Peter Lawrey