提高Java程序内存效率

程序

我们都知道Java程序之所以被广大程序员青睐,很大的一个原因是因为Java有GC(垃圾收集),不用程序员花很大的精力来解决内存释放和泄漏问题。而这些问题总是C/C++程序员需要花很大精力来认真地面对的。

问题总是双面的,GC给我们带来了很大的快乐,释放了程序员很多的精力和时间,但是在某些时候也会给我们带来一些小小的麻烦。Java里的Object并非交给GC去释放就可高枕无忧了,下面从JDK1.4的Demo中Java2D的Memory Monitor说起。

先看看Memory Monitor单独运行的效果。

可以看到因为有个While循环,GC释放内存有一定的时间,在这个时间中间,内存消耗的很厉害。峰值达到923K。程序代码的如下:

//SysGcMain.java Created on 9:15:59

package com.gx2.system;

/**

* @author Frank Gao @version 1.00

* Copy right by GX2 Studio 2003

* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.

*

* Redistribution and use in source……以后省略

*/

/*

* @(#)MemoryMonitor.java 1.32 03/01/23

*/

import java.awt.*;

import java.awt.event.*;

import java.awt.image.BufferedImage;

import java.awt.geom.Line2D;

import java.awt.geom.Rectangle2D;

import java.util.Date;

import javax.swing.*;

import javax.swing.border.EtchedBorder;

import javax.swing.border.TitledBorder;

/**

* Tracks Memory allocated & used, displayed in graph form.

*/

public class SysGcMain extends JPanel {

static JCheckBox dateStampCB = new JCheckBox("Output Date Stamp");

public Surface surf;

JPanel controls;

boolean doControls;

JTextField tf;

public SysGcMain() {

setLayout(new BorderLayout());

setBorder(new TitledBorder(new EtchedBorder(), "Memory Monitor"));

add(surf = new Surface());

controls = new JPanel();

controls.setPreferredSize(new Dimension(135,80));

Font font = new Font("serif", Font.PLAIN, 10);

JLabel label = new JLabel("Sample Rate");

label.setFont(font);

label.setForeground(Color.black);

controls.add(label);

tf = new JTextField("1000");

tf.setPreferredSize(new Dimension(45,20));

controls.add(tf);

controls.add(label = new JLabel("ms"));

label.setFont(font);

label.setForeground(Color.black);

controls.add(dateStampCB);

dateStampCB.setFont(font);

addMouseListener(new MouseAdapter() {

public void mouseClicked(MouseEvent e) {

removeAll();

if ((doControls = !doControls)) {

surf.stop();

add(controls);

} else {

try {

surf.sleepAmount = Long.parseLong(tf.getText().trim());

} catch (Exception ex) {}

surf.start();

add(surf);

}

validate();

repaint();

}

});

}

public class Surface extends JPanel implements Runnable {

public Thread thread;

public long sleepAmount = 1000;

private int w, h;

private BufferedImage bimg;

private Graphics2D big;

private Font font = new Font("Times New Roman", Font.PLAIN, 11);

private Runtime r = Runtime.getRuntime();

private int columnInc;

private int pts[];

private int ptNum;

private int ascent, descent;

private float freeMemory, totalMemory;

private Rectangle graphOutlineRect = new Rectangle();

private Rectangle2D mfRect = new Rectangle2D.Float();

private Rectangle2D muRect = new Rectangle2D.Float();

private Line2D graphLine = new Line2D.Float();

private Color graphColor = new Color(46, 139, 87);

private Color mfColor = new Color(0, 100, 0);

private String usedStr;

public Surface() {

setBackground(Color.black);

addMouseListener(new MouseAdapter() {

public void mouseClicked(MouseEvent e) {

if (thread == null) start(); else stop();

}

});

}

public Dimension getMinimumSize() {

return getPreferredSize();

}

public Dimension getMaximumSize() {

return getPreferredSize();

}

public Dimension getPreferredSize() {

return new Dimension(135,80);

}

public void paint(Graphics g) {

if (big == null) {

return;

}

big.setBackground(getBackground());

big.clearRect(0,0,w,h);

float freeMemory = (float) r.freeMemory();

float totalMemory = (float) r.totalMemory();

// .. Draw allocated and used strings ..

big.setColor(Color.green);

big.drawString(String.valueOf((int) totalMemory/1024) + "K allocated", 4.0f, (float) ascent+0.5f);

usedStr = String.valueOf(((int) (totalMemory - freeMemory))/1024)

+ "K used";

big.drawString(usedStr, 4, h-descent);

// Calculate remaining size

float ssH = ascent + descent;

float remainingHeight = (float) (h - (ssH*2) - 0.5f);

float blockHeight = remainingHeight/10;

float blockWidth = 20.0f;

float remainingWidth = (float) (w - blockWidth - 10);

// .. Memory Free ..

big.setColor(mfColor);

int MemUsage = (int) ((freeMemory / totalMemory) * 10);

int i = 0;

for ( ; i < MemUsage ; i++) {

mfRect.setRect(5,(float) ssH+i*blockHeight,

blockWidth,(float) blockHeight-1);

big.fill(mfRect);

}

// .. Memory Used ..

big.setColor(Color.green);

for ( ; i < 10; i++) {

muRect.setRect(5,(float) ssH+i*blockHeight,

blockWidth,(float) blockHeight-1);

big.fill(muRect);

}

// .. Draw History Graph ..

big.setColor(graphColor);

int graphX = 30;

int graphY = (int) ssH;

int graphW = w - graphX - 5;

int graphH = (int) remainingHeight;

graphOutlineRect.setRect(graphX, graphY, graphW, graphH);

big.draw(graphOutlineRect);

int graphRow = graphH/10;

// .. Draw row ..

for (int j = graphY; j <= graphH+graphY; j += graphRow) {

graphLine.setLine(graphX,j,graphX+graphW,j);

big.draw(graphLine);

}

// .. Draw animated column movement ..

int graphColumn = graphW/15;

if (columnInc == 0) {

columnInc = graphColumn;

}

for (int j = graphX+columnInc; j < graphW+graphX; j+=graphColumn) {

graphLine.setLine(j,graphY,j,graphY+graphH);

big.draw(graphLine);

}

--columnInc;

if (pts == null) {

pts = new int[graphW];

ptNum = 0;

} else if (pts.length != graphW) {

int tmp[] = null;

if (ptNum < graphW) {

tmp = new int[ptNum];

System.arraycopy(pts, 0, tmp, 0, tmp.length);

} else {

tmp = new int[graphW];

System.arraycopy(pts, pts.length-tmp.length, tmp, 0, tmp.length);

ptNum = tmp.length - 2;

}

pts = new int[graphW];

System.arraycopy(tmp, 0, pts, 0, tmp.length);

} else {

big.setColor(Color.yellow);

pts[ptNum] = (int)(graphY+graphH*(freeMemory/totalMemory));

for (int j=graphX+graphW-ptNum, k=0;k < ptNum; k++, j++) {

if (k != 0) {

if (pts[k] != pts[k-1]) {

big.drawLine(j-1, pts[k-1], j, pts[k]);

} else {

big.fillRect(j, pts[k], 1, 1);

}

}

}

if (ptNum+2 == pts.length) {

// throw out oldest point

for (int j = 1;j < ptNum; j++) {

pts[j-1] = pts[j];

}

--ptNum;

} else {

ptNum++;

}

}

g.drawImage(bimg, 0, 0, this);

}

public void start() {

thread = new Thread(this);

thread.setPriority(Thread.MIN_PRIORITY);

thread.setName("MemoryMonitor");

thread.start();

}

public synchronized void stop() {

thread = null;

notify();

}

public void run() {

Thread me = Thread.currentThread();

while (thread == me && !isShowing() || getSize().width == 0) {

try {

thread.sleep(500);

} catch (InterruptedException e) { return; }

}

while (thread == me && isShowing()) {

Dimension d = getSize();

if (d.width != w || d.height != h) {

w = d.width;

h = d.height;

bimg = (BufferedImage) createImage(w, h);

big = bimg.createGraphics();

big.setFont(font);

FontMetrics fm = big.getFontMetrics(font);

ascent = (int) fm.getAscent();

descent = (int) fm.getDescent();

}

repaint();

try {

thread.sleep(sleepAmount);

} catch (InterruptedException e) { break; }

if (SysGcMain.dateStampCB.isSelected()) {

System.out.println(new Date().toString() + " " + usedStr);

}

//add by 忘记理想 2004-11-1

// 不强制GC的话,因为while循环,内存会消耗的很厉害

// 加上下面两句,可以保证内存消耗平稳

Runtime.getRuntime().freeMemory();

Runtime.getRuntime().gc();

}

thread = null;

}

}

public static void main(String s[]) {

final SysGcMain demo = new SysGcMain();

WindowListener l = new WindowAdapter() {

public void windowClosing(WindowEvent e) {System.exit(0);}

public void windowDeiconified(WindowEvent e) { demo.surf.start(); }

public void windowIconified(WindowEvent e) { demo.surf.stop(); }

};

JButton button = new JButton("Force GC");

button.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent event){

Runtime.getRuntime().freeMemory();

Runtime.getRuntime().gc();

}

});

JFrame f = new JFrame("Frank Gao - MemoryMonitor");

f.addWindowListener(l);

f.getContentPane().add("Center", demo);

f.getContentPane().add(button,BorderLayout.SOUTH);

f.pack();

f.setSize(new Dimension(200,200));

f.setVisible(true);

demo.surf.start();

}

}

在while循环中加入强制gc,内存峰值得到了很好的控制维持水平。

Runtime.getRuntime().freeMemory();

Runtime.getRuntime().gc();

由此可以考虑在,程序while等比较好内存的地方采用上述方法,降低内存峰值,提高内存效率。

时间: 2024-08-01 11:05:41

提高Java程序内存效率的相关文章

对《30个提高Web程序执行效率的好经验》的理解

阅读了博客园发布的IT文章<30个提高Web程序执行效率的好经验>,这30条准则对我们web开发是非常有用的,不过大家可能对其中的一些准则是知其然而不知其所以然. 下面是我对这些准则的理解和分析,有些有关JS性能的准则,我也测试了它们的差异,大家可以下载DEMO页面,如有理解不正确的地方,请大家指正.也非常欢迎大家补充. 测试环境: OS:Vista; Processor:3.40GHz; Memory: 2.00GB; System type: 32-bit Operating System

如何提高WEB程序的效率 (第一篇SQL篇)  (转)

web|程序 如何提高WEB程序的效率 (第一篇"SQL篇") 很多网友非常不喜欢用ASP来编程,他们总是抱怨说ASP程序太慢,效率太低.更希望用PHP,JSP等来写程序.其实不能从 "认为" 这个角度来看问题 ,而应该从实际中看问题,ASP真的很慢的吗,那么微软的站为何用ASP也不慢呢?PHP真的很快吗,其实它也仍然是解释性的语言.只不过在Linux下的结合比较好而以.JSP的开发也不会简单到何处,而且要通过JDBC-ODBC桥才能连接ACCESS库等,这种情况下

找出Java程序内存溢出的元凶

我曾经在刚入行的时候做过一个小的swing程序,用到了java SE,swing,Thread等东东,当初经验少 也没有做过严格的性能测试,布到生产环境用了一段时间后发现那个小程序有时候会抛 java.lang.OutofMemoryError异常,就是java的内存溢出.当时也上网查了不少资料,试过一些办法,代 码也稍微做了些优化,但是有一个问题我始终是找不到解决的方案 - 不知为什么子窗体关闭后java的垃 圾回收机制无法回收其资源,因为这个Java程序可能要经常开关一些子窗体,那么这些子窗

JAVA程序内存溢出问题原因分析_java

本文较为详细的分析了JAVA程序内存溢出问题原因.分享给大家供大家参考.具体如下: 遇到一个线上系统报 java.lang.OutOfMemoryError: PermGen space 错误,需要定位一下问题.很久之前到时弄过这个,现在还真有点不记得了,但这个真的是一个非常有意思的问题,值得好好研究一下.首先第一反应当然是加上-XX:+PrintGCDetails参数来看具体的GC日志,但是由于程序是tomcat启动的,担心里面封装的东西太多不好定位,既然在windows下面,所以还是借助可视

java程序内存不下降,但是也没有内存泄露怎么分析?

问题描述 java程序内存不下降,但是也没有内存泄露怎么分析? 我们用java开发的程序.运行过程中使用任务管理器观察内存可以达到700M.使用java自带的jvisualvm.exe查看内存申请了200多用了100M,请问剩下的500M去哪里了.用什么方法可以找到这些内存的去向.

如何提高WEB程序的效率 (第一篇)

web|程序 很多网友非常不喜欢用ASP来编程,他们总是抱怨说ASP程序太慢,效率太低.更希望用PHP,JSP等来写程序.其实不能从 "认为" 这个角度来看问题 ,而应该从实际中看问题,ASP真的很慢的吗,那么微软的站为何用ASP也不慢呢?PHP真的很快吗,其实它也仍然是解释性的语言.只不过在Linux下的结合比较好而以.JSP的开发也不会简单到何处,而且要通过JDBC-ODBC桥才能连接ACCESS库等,这种情况下效率也不高. 其实,三种语言各有特点,就是优,缺点.作为一个程序员不应

如何提高WEB程序的效率

web|程序 很多网友非常不喜欢用ASP来编程,他们总是抱怨说ASP程序太慢,效率太低.更希望用PHP,JSP等来写程序.其实不能从 "认为" 这个角度来看问题 ,而应该从实际中看问题,ASP真的很慢的吗,那么微软的站为何用ASP也不慢呢?PHP真的很快吗,其实它也仍然是解释性的语言.只不过在Linux下的结合比较好而以.JSP的开发也不会简单到何处,而且要通过JDBC-ODBC桥才能连接ACCESS库等,这种情况下效率也不高. 其实,三种语言各有特点,就是优,缺点.作为一个程序员不应

教你用Type Hint提高Python程序开发效率_python

简介 Type Hint(或者叫做PEP-484)提供了一种针对Python程序的类型标注标准. 为什么使用Type Hint?对于动态语言而言,常常出现的情况是当你写了一段代码后,隔段时间你可能忘记这个方法的原型是什么样子的了,你也不清楚具体应该传入什么类型的参数,这样往往需要你去阅读代码才能定义每个类型具体是什么.或者当你使用一个文档并不是特别完全的第三方库,你不知道这个库应该如何使用,这都会很痛苦. 现在,借助Type Hint,你可以实现:      1.实现类型检查,防止运行时出现的类

Java程序内存分析:使用mat工具分析内存占用

    MAT 不是一个万能工具,它并不能处理所有类型的堆存储文件.但是比较主流的厂家和格式,例如 Sun, HP, SAP 所采用的 HPROF 二进制堆存储文件,以及 IBM 的 PHD 堆存储文件等都能被很好的解析.下面来看看要怎么做呢,也许对你有用.官方文档:http://help.eclipse.org/luna/index.jsp?topic=/org.eclipse.mat.ui.help/welcome.html 造成OutOfMemoryError原因一般有2种: 1.内存泄露