Download Free English Song Albums Here

Friday

Java Simple Example-7

Java Get Memory Usage:

If you have prior worked on C or C++ language, you must be aware of that unlike c++,  java don't tell that how much memory is occupied by an object defined in the program.
In this example, we are going to get the used memory from the actual memory. As you know in Java programming memory can be allocated in various forms such as Stack and Heap etc.. you will see that in the given example code output.

Java Code to Get Memory Usage

public class GetMemoryUsage
{
  public static void main (String [] args) throws Exception
  {
  run ();
  memoryUsed ();
  final int count = 100000;
  Object [] object = new Object [count];
  long heap1 = 0;
  for (int i = -1; i < count; ++ i)
  {
  Object obj = null
  obj = new Object (); 
  if (i >= 0)
  object [i] = obj;
  else
  {
  obj = null
  run ();
  heap1 = memoryUsed ();
  }
  }
  run ();
  long heap2 = memoryUsed (); 
  System.out.println ("'before' heap: " + heap1 +
  ", 'after' heap: " + heap2);
  System.out.println ("heap delta: " + (heap2 - heap1) );
  for (int i = 0; i < count; ++ i) object [i] = null;
  object = null;
  }
 static void run () throws Exception
  {
  for (int j = 0; j < 4; ++ j) _run ();
  }
 static void _run () throws Exception
  {
  long mem1 = memoryUsed (), mem2 = Long.MAX_VALUE;
  for (int i = 0; (mem1 < mem2) && (i < 500); ++ i)
  {
  runtime.runFinalization ();
  runtime.gc ();
  Thread.currentThread ().yield ();
  mem2 = mem1;
  mem1 = memoryUsed ();
  }
  }
 static long memoryUsed ()
  {
  return runtime.totalMemory () - runtime.freeMemory ();
  }
  
 static final Runtime runtime = Runtime.getRuntime ();
}

Output will be displayed as:



Related Post:

No comments:

Post a Comment

More Posts

Justin Bieber Albums Download - Under the Mistletoe 2011 Justin Bieber feat. Usher - The Christmas Song Justin bieber 2011 New Album And Top Songs Justin Bieber Albums - Never Say Never - The Remixes 2011 Justin bieber Albums - Justin Bieber - My Worlds The Collection (Acoustic) 2010 Justin Bieber Songs - My world 2.0 (2010) - Justin Bieber - Mp3.320 kbps.VBR - Inc Covers & bonus tracks -Mediafire
Justin Bieber Albums Download - Under the Mistletoe 2011 Justin Bieber feat. Usher - The Christmas Song Justin bieber 2011 New Album And Top Songs Justin Bieber Albums - Never Say Never - The Remixes 2011 Justin bieber Albums - Justin Bieber - My Worlds The Collection (Acoustic) 2010 Justin Bieber Songs - My world 2.0 (2010) - Justin Bieber - Mp3.320 kbps.VBR - Inc Covers & bonus tracks -Mediafire
50 Cent Albums Download (8) Akon Albums Download (11) Albums Released This November (17) Albums Released This October (24) Ashley Tisdale Albums Download (2) Avril Lavigne Albums Download (4)
+ Grab this