方法1 建一个jsp页面 :<%@page
contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd
">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JVM memory</title>
</head>
<body>
<%
double total = (Runtime.getRuntime().totalMemory()) / (1024.0 * 1024);
double max = (Runtime.getRuntime().maxMemory()) / (1024.0 * 1024);
double free = (Runtime.getRuntime().freeMemory()) / (1024.0 * 1024);
out.println("Java 虚拟机试图使用的最大内存量(当前JVM的最大可用内存)maxMemory(): " + max + "MB<br/>");
out.println("Java 虚拟机中的内存总量(当前JVM占用的内存总数)totalMemory(): " + total + "MB<br/>");
out.println("Java 虚拟机中的空闲内存量(当前JVM空闲内存)freeMemory(): " + free + "MB<br/>");
out.println("因为JVM只有在需要内存时才占用物理内存使用,所以freeMemory()的值一般情况下都很 小,<br/>" +
"而JVM实际可用内存并不等于freeMemory(),而应该等于 maxMemory()-totalMemory()+freeMemory()。<br/>");
out.println("JVM实际可用内存: " + (max - total + free) + "MB<br/>");
out.println("jspcn");
%>
</body>
</html>
法2 :
Tomcat本身带的应用manager可以进行服务器状态的监控JVM内存。为了运行该程序,需要创建角色manager和对应的用户。
创建位置在conf/tomcat-users.xml中,内容如下所示:
xml version ='1.0' encoding ='utf-8' ?>
- < tomcat-users > < role rolename = "tomcat" />
- < role rolename = "role1" />
- < role rolename = "manager" />
- < role rolename = "admin" />
- < user username = "tomcat" password = "tomcat" roles = "tomcat" />
- < user username = "both" password = "tomcat" roles = "tomcat,role1" />
- < user username = "role1" password = "tomcat" roles = "role1" />
- < user username = "admin" password = "tomcat" roles = "admin,manager" />
- tomcat-users >
创建了角色manager和用户 admin/tomcat后就可以使用manager应用了。
在IE中键入httpp://localhost:8080,进入tomcat的主界面,然后选择左面的
下 的Tomcat Manager ,输入用户名和密码(admin/tomcat),就进入了 manager的界面,Administration 选择最右方的“Server Status ”,便可以看到JVM的占用情况。
Free memory: 3.69 MB Total memory: 10.60 MB Max memory: 63.31 MB
Free memory:当前可用的内存;
Total memory:当前已经分配的Tomcat JVM内存;
Max memory:当前允许分配的最大Tomcat JVM内存;