尽管Java提供了自动垃圾收集
, 有时你会想知道对象堆有多大, 还剩下多少。该信息可用于检查代码的效率, 并大约检查可实例化某种类型的更多对象。要获得这些值, 我们使用
和
方法。
众所周知, Java的垃圾回收器会定期运行以回收未使用的对象。我们可以通过调用
GC()
方法。尝试拨打电话是一件好事
GC()
然后打电话
.
方法:
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 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 memeory
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( "Memeory 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 memeory 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
如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。