How to calculate the memory occupied by Java objects

xiaoxiao2021-03-06  112

Java has a good place to java's garbage collection mechanism, this mechanism is integrated into JVM, hidden by programmers and opaque. In this case, how to get a memory consumed by an object? Once I saw that someone used the following method to calculate: The java.lang.Runtime.FreeMemory () method is called before and after generating the object, and then the difference between the two is the amount of memory consumed by the Object.

The code for this method is:

Long totalmem = java.lang.Runtime.FreeMemory ();

Object mybigObject = null;

System.out.println ("You Just Got Rid of" Totalmem

- java.lang.Runtime.FreeMemory ());

This idea is right, but in fact, JVM freeMemory often does not correctly reactively reacting the actual Free Memory. For example, free memory will shrink when JVM should be collected. And if the time determines that the garbage collection occurs after the Object generated, the amount of memory consumed by the Object consumption is incremented by calling java.lang.Runtime.FreeMemory (). In Java Expert By Tony Sintes, "Discover How much memory an object consumes" mentioned Runtime.Getruntime (). TotalMemory (); and calculate the amount of memory that is consumed. Source code of by tony sintes:

Public class memory {

PRIVATE = 500;

Public static void main (string [] args)

Throws exception {

Object [] array = new object [_size];

Runtime.getRuntime (). Gc ();

Long Start = runtime.getRuntime (). TotalMemory ();

For (int i = 0; i <_size; i ) {

Array [i] = new object ();

}

Runtime.getRuntime (). Gc ();

Long end = runtime.getRuntime (). Totalmemory ();

Long Difference = (START - END) / _SIZE;

System.out.println (Difference "BYTES USED

Per object on avee ");

}

}

In fact, this method is basically correct, but by tony sintes neglects a little, it is just runtime.getruntime (). GC (); does not really complete garbage collection, that is, JVM memory is not stable. So, only when memory is no longer caused, or it is stable, we may say that garbage collection has been completed. How can I really ensure that JVM garbage collection is basically completed? The code that implements this feature is as follows:

Private static final runtime s_runtime =

Runtime.getRuntime ();

Private static long buyMemory ()

{

Return S_Runtime.TotalMemory () -

S_Runtime.FreeMemory ();

Private static void rungc () THROWS EXCEPTION

{

Long usemedmem1 = usedmemory (), usedmem2 = long.max_value;

For (int i = 0; (usemedmem1

{

S_Runtime.RunFinalization ();

S_Runtime.gc ();

Thread.currentthread () .yeld ();

Usedmem2 = usedMem1;

Usedmem1 = usemedMemory ();

}

}

Rungc () can help us really determine the completion of garbage collection (accurately, it should be said to be basically completed).

转载请注明原文地址:https://www.9cbs.com/read-125750.html

New Post(0)