java代码如何获取可用内存呢?
下文笔者通过示例的方式讲述java代码获取可用内存的方法分享,如下所示:
实现思路: 借助Runtime.getRuntime()类即可获取指定的信息例:
package com.java265.other; import java.io.File; public class Test11 { /** * java265.com 示例演示 */ public static void main(String[] args) throws Exception { /* Total number of processors or cores available to the JVM */ System.out.println("Available processors (cores): " + Runtime.getRuntime().availableProcessors()); /* Total amount of free memory available to the JVM */ System.out.println("Free memory (bytes): " + Runtime.getRuntime().freeMemory()); /* This will return Long.MAX_VALUE if there is no preset limit */ long maxMemory = Runtime.getRuntime().maxMemory(); /* Maximum amount of memory the JVM will attempt to use */ System.out.println("Maximum memory (bytes): " + (maxMemory == Long.MAX_VALUE ? "no limit" : maxMemory)); /* Total memory currently in use by the JVM */ System.out.println("Total memory (bytes): " + Runtime.getRuntime().totalMemory()); /* Get a list of all filesystem roots on this system */ File[] roots = File.listRoots(); /* For each filesystem root, print some info */ for (File root : roots) { System.out.println("File system root: " + root.getAbsolutePath()); System.out.println("Total space (bytes): " + root.getTotalSpace()); System.out.println("Free space (bytes): " + root.getFreeSpace()); System.out.println("Usable space (bytes): " + root.getUsableSpace()); } } } --------运行以上代码,将输出以下信息------ Available processors (cores): 8 Free memory (bytes): 264491200 Maximum memory (bytes): 4229955584 Total memory (bytes): 266338304 File system root: C:\ Total space (bytes): 161469165568 Free space (bytes): 29989670912 Usable space (bytes): 29989670912 File system root: D:\ Total space (bytes): 214748360704 Free space (bytes): 27861917696 Usable space (bytes): 27861917696 File system root: E:\ Total space (bytes): 128849014784 Free space (bytes): 109176647680 Usable space (bytes): 109176647680
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。