如何在Java中找到最大内存、可用内存和总内存?
尽管Java提供了自动垃圾回收,但有时您会想知道对象堆有多大以及还剩下多少。此信息可用于检查代码的效率并大致检查可以实例化特定类型的对象的数量。为了获得这些值,我们使用
totalMemory()和freeMemory方法。
正如我们所知,Java 的垃圾收集器会定期运行以回收未使用的对象。我们可以通过调用gc()方法按需调用垃圾收集器。一个很好的尝试是调用gc()然后调用freeMemory() 。
方法:
- void gc():运行垃圾收集器。调用此方法表明Java虚拟机将努力回收未使用的对象,以使它们当前占用的内存可用于快速重用。当控制从方法调用返回时,虚拟机已尽最大努力回收所有丢弃的对象。
句法:
public void gc()
Returns: NA.
Exception: NA.
- long freeMemory():此方法返回Java虚拟机中的可用内存量。调用 gc 方法可能会导致 freeMemory 返回的值增加。
句法:
public long freeMemory()
Returns: an approximation to the total
amount of memory currently available for
future allocated objects, measured in bytes.
Exception: NA.
- long totalMemory():此方法返回Java虚拟机中的内存总量。此方法返回的值可能会随时间变化,具体取决于主机环境。
句法:
public long totalMemory()
Returns: the total amount of memory
currently available for current and future
objects, measured in bytes.
Exception: NA.
Java
// Java code illustrating gc(), freeMemory()
// and totalMemory() methods
class memoryDemo
{
public static void main(String arg[])
{
Runtime gfg = Runtime.getRuntime();
long memory1, memory2;
Integer integer[] = new Integer[1000];
// checking the total memory
System.out.println("Total memory is: "
+ gfg.totalMemory());
// checking free memory
memory1 = gfg.freeMemory();
System.out.println("Initial free memory: "
+ memory1);
// calling the garbage collector on demand
gfg.gc();
memory1 = gfg.freeMemory();
System.out.println("Free memory after garbage "
+ "collection: " + memory1);
// allocating integers
for (int i = 0; i < 1000; i++)
integer[i] = new Integer(i);
memory2 = gfg.freeMemory();
System.out.println("Free memory after allocation: "
+ memory2);
System.out.println("Memory used by allocation: " +
(memory1 - memory2));
// discard integers
for (int i = 0; i < 1000; i++)
integer[i] = null;
gfg.gc();
memory2 = gfg.freeMemory();
System.out.println("Free memory after "
+ "collecting discarded Integers: " + memory2);
}
}
输出:
Total memory is: 128974848
Initial free memory: 126929976
Free memory after garbage collection: 128632384
Free memory after allocation: 127950744
Memory used by allocation: 681640
Free memory after collecting discarded Integers: 128643696