jvm 内存监控2
引用:http://www.189works.com/article-75562-1.html
一个类对JVM可用内存进行了监测
- import java.util.Timer;
- import java.util.TimerTask;
- import java.util.Calendar;
- import java.util.GregorianCalendar;
- /**
- Title:GCTimerTask
- * @author zhuangyan
- * @msn:nacl_zhuang@hotmail.com
- * @qq:368924454
- * @version 1.0
- */
- public class GCTimerTask
- extends TimerTask {
- private static GCTimerTask instance = null;
- public void run() {
- Calendar cal = new GregorianCalendar();
- int hour24 = cal.get(Calendar.HOUR_OF_DAY); // 0..23
- int min = cal.get(Calendar.MINUTE); // 0..59
- System.out.print("["+String.valueOf(hour24)+":"+String.valueOf(min)+"]");
- System.out.println("JVM可用内存:" + java.lang.Runtime.getRuntime().
- freeMemory() / (1024*1024)+"M/"+java.lang.Runtime.getRuntime()
.totalMemory()/(1024*1024)+"M" ); - System.gc();
- }
- private void startWork()
- {
- Timer t = new Timer();
- t.schedule(instance,0,1000*60);
- }
- public static GCTimerTask getInstance()
- {
- if(instance==null) {
- instance = new GCTimerTask();
- instance.startWork();
- }
- return instance;
- }
- }
这个类虽然简单,但初学者从中应该学到
1)timer类的用法
2)java.lang.Runtime.getRuntime().freeMemory(),java.lang.Runtime.getRuntime().totalMemory(),System.gc()
这三个方法的使用,需要说明的是System.gc()并不能**JVM马上释放内存,如果那样,我的内存溢出问题早就解决了.
3)getInstance()单例模式,
4)最后的就是怎么用这个类的问题,我把它放到了EncodingFilter类中,现在很多JSP程序中都有这个类吧
- public final void init(final FilterConfig arg0) throws ServletException {
- GCTimerTask.getInstance();
- this.filterConfig = arg0;
- this.encoding = filterConfig.getInitParameter("encoding");
- String value = filterConfig.getInitParameter("ignore");
- if (value == null) {
- this.ignore = true;
- }
- else if (value.equalsIgnoreCase("true")) {
- this.ignore = true;
- }
- else if (value.equalsIgnoreCase("yes")) {
- this.ignore = true;
- }
- else {
- this.ignore = false;
- }
- }
JVM可用内存:405M/508M