有时搞web开发的时候经常会出现OOM(out of memory)、permGen space不足的情况,其实就是jvm的内存不足了,下面的方法可以监视jvm的使用情况
(原方法来自http://developer.51cto.com/art/200907/134171.htm)
import java.util.Timer; import java.util.TimerTask; import java.util.Calendar; import java.util.GregorianCalendar; 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; } public static void main(String[] args) { GCTimerTask.getInstance(); } }
运行该程序后,每隔一分钟,console就会输出jvm的可用内存信息了,截图如下: