`

java可视化显示内存使用情况

阅读更多
package memoryManage;

/*
 * @(#)MemoryMonitor.java	1.3 05/11/17
 * 
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 * 
 * -Redistribution in binary form must reproduce the above copyright notice, 
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 * 
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may 
 * be used to endorse or promote products derived from this software without 
 * specific prior written permission.
 * 
 * This software is provided "AS IS," without a warranty of any kind. ALL 
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST 
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, 
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY 
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, 
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 * 
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */

/*
 * @(#)MemoryMonitor.java	1.3 05/11/17
 */

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;
import java.lang.management.*;
import java.util.*;

/**
 * Demo code which plots the memory usage by all memory pools. The memory usage
 * is sampled at some time interval using java.lang.management API. This demo
 * code is modified based java2d MemoryMonitor demo.
 */
class MemoryMonitor extends JPanel {

	static JCheckBox dateStampCB = new JCheckBox("Output Date Stamp");
	public Surface surf;
	JPanel controls;
	boolean doControls;
	JTextField tf;
	// Get memory pools.
	static java.util.List<MemoryPoolMXBean> mpools = ManagementFactory
			.getMemoryPoolMXBeans();
	// Total number of memory pools.
	static int numPools = mpools.size();

	public MemoryMonitor() {
		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.red);
		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.red);
		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;
		public int usageHistCount = 20000;
		private int w, h;
		private BufferedImage bimg;
		private Graphics2D big;
		private Font font = new Font("Times New Roman", Font.PLAIN, 11);
		private int columnInc;
		private float usedMem[][];
		private int ptNum[];
		private int ascent, descent;
		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();
				}
			});
			int i = 0;
			usedMem = new float[numPools][];
			ptNum = new int[numPools];
		}

		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);

			h = h / ((numPools + numPools % 2) / 2);
			w = w / 2;

			int k = 0; // index of memory pool.
			for (int i = 0; i < 2; i++) {
				for (int j = 0; j < (numPools + numPools % 2) / 2; j++) {
					plotMemoryUsage(w * i, h * j, w, h, k);
					if (++k >= numPools) {
						i = 3;
						j = (numPools + numPools % 2) / 2;
						break;
					}
				}
			}
			g.drawImage(bimg, 0, 0, this);
		}

		public void plotMemoryUsage(int x1, int y1, int x2, int y2, int npool) {

			MemoryPoolMXBean mp = mpools.get(npool);
			float usedMemory = mp.getUsage().getUsed();
			float totalMemory = mp.getUsage().getMax();

			// .. Draw allocated and used strings ..
			big.setColor(Color.green);

			// Print Max memory allocated for this memory pool.
			big.drawString(String.valueOf((int) totalMemory / 1024) + "K Max ",
					x1 + 4.0f, (float) y1 + ascent + 0.5f);
			big.setColor(Color.yellow);

			// Print the memory pool name.
			big.drawString(mp.getName(), x1 + x2 / 2, (float) y1 + ascent
					+ 0.5f);

			// Print the memory used by this memory pool.
			usedStr = String.valueOf((int) usedMemory / 1024) + "K used";
			big.setColor(Color.green);
			big.drawString(usedStr, x1 + 4, y1 + y2 - descent);

			// Calculate remaining size
			float ssH = ascent + descent;
			float remainingHeight = (float) (y2 - (ssH * 2) - 0.5f);
			float blockHeight = remainingHeight / 10;
			float blockWidth = 20.0f;
			float remainingWidth = (float) (x2 - blockWidth - 10);

			// .. Memory Free ..
			big.setColor(mfColor);
			int MemUsage = (int) (((totalMemory - usedMemory) / totalMemory) * 10);
			int i = 0;
			for (; i < MemUsage; i++) {
				mfRect.setRect(x1 + 5, (float) y1 + ssH + i * blockHeight,
						blockWidth, (float) blockHeight - 1);
				big.fill(mfRect);
			}

			// .. Memory Used ..
			big.setColor(Color.green);
			for (; i < 10; i++) {
				muRect.setRect(x1 + 5, (float) y1 + ssH + i * blockHeight,
						blockWidth, (float) blockHeight - 1);
				big.fill(muRect);
			}

			// .. Draw History Graph ..
			if (remainingWidth <= 30)
				remainingWidth = (float) 30;
			if (remainingHeight <= ssH)
				remainingHeight = (float) ssH;
			big.setColor(graphColor);
			int graphX = x1 + 30;
			int graphY = y1 + (int) ssH;
			int graphW = (int) remainingWidth;
			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;

			// Plot memory usage by this memory pool.
			if (usedMem[npool] == null) {
				usedMem[npool] = new float[usageHistCount];
				ptNum[npool] = 0;
			}

			// save memory usage history.
			usedMem[npool][ptNum[npool]] = usedMemory;

			big.setColor(Color.yellow);

			int w1; // width of memory usage history.
			if (ptNum[npool] > graphW) {
				w1 = graphW;
			} else {
				w1 = ptNum[npool];
			}

			for (int j = graphX + graphW - w1, k = ptNum[npool] - w1; k < ptNum[npool]; k++, j++) {
				if (k != 0) {
					if (usedMem[npool][k] != usedMem[npool][k - 1]) {
						int h1 = (int) (graphY + graphH
								* ((totalMemory - usedMem[npool][k - 1]) / totalMemory));
						int h2 = (int) (graphY + graphH
								* ((totalMemory - usedMem[npool][k]) / totalMemory));
						big.drawLine(j - 1, h1, j, h2);
					} else {
						int h1 = (int) (graphY + graphH
								* ((totalMemory - usedMem[npool][k]) / totalMemory));
						big.fillRect(j, h1, 1, 1);
					}
				}
			}
			if (ptNum[npool] + 2 == usedMem[npool].length) {
				// throw out oldest point
				for (int j = 1; j < ptNum[npool]; j++) {
					usedMem[npool][j - 1] = usedMem[npool][j];
				}
				--ptNum[npool];
			} else {
				ptNum[npool]++;
			}
		}

		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 (MemoryMonitor.dateStampCB.isSelected()) {
					System.out.println(new Date().toString() + " " + usedStr);
				}
			}
			thread = null;
		}
	}

	// Test thread to consume memory
	static class Memeater extends ClassLoader implements Runnable {
		Object y[];

		public Memeater() {
		}

		public void run() {
			y = new Object[10000000];
			int k = 0;
			while (true) {
				if (k == 5000000)
					k = 0;
				y[k++] = new Object();
				try {
					Thread.sleep(20);
				} catch (Exception x) {
				}

				// to consume perm gen storage
				try {
					// the classes are small so we load 10 at a time
					for (int i = 0; i < 10; i++) {
						loadNext();
					}
				} catch (ClassNotFoundException x) {
					// ignore exception
				}

			}

		}

		Class loadNext() throws ClassNotFoundException {

			// public class TestNNNNNN extends java.lang.Object{
			// public TestNNNNNN();
			// Code:
			// 0: aload_0
			// 1: invokespecial #1; //Method java/lang/Object."<init>":()V
			// 4: return
			// }

			int begin[] = { 0xca, 0xfe, 0xba, 0xbe, 0x00, 0x00, 0x00, 0x30,
					0x00, 0x0a, 0x0a, 0x00, 0x03, 0x00, 0x07, 0x07, 0x00, 0x08,
					0x07, 0x00, 0x09, 0x01, 0x00, 0x06, 0x3c, 0x69, 0x6e, 0x69,
					0x74, 0x3e, 0x01, 0x00, 0x03, 0x28, 0x29, 0x56, 0x01, 0x00,
					0x04, 0x43, 0x6f, 0x64, 0x65, 0x0c, 0x00, 0x04, 0x00, 0x05,
					0x01, 0x00, 0x0a, 0x54, 0x65, 0x73, 0x74 };

			int end[] = { 0x01, 0x00, 0x10, 0x6a, 0x61, 0x76, 0x61, 0x2f, 0x6c,
					0x61, 0x6e, 0x67, 0x2f, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74,
					0x00, 0x21, 0x00, 0x02, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00,
					0x00, 0x01, 0x00, 0x01, 0x00, 0x04, 0x00, 0x05, 0x00, 0x01,
					0x00, 0x06, 0x00, 0x00, 0x00, 0x11, 0x00, 0x01, 0x00, 0x01,
					0x00, 0x00, 0x00, 0x05, 0x2a, 0xb7, 0x00, 0x01, 0xb1, 0x00,
					0x00, 0x00, 0x00, 0x00, 0x00 };

			// TestNNNNNN

			String name = "Test" + Integer.toString(count++);

			byte value[];
			try {
				value = name.substring(4).getBytes("UTF-8");
			} catch (java.io.UnsupportedEncodingException x) {
				throw new Error();
			}

			// construct class file

			int len = begin.length + value.length + end.length;
			byte b[] = new byte[len];
			int i, pos = 0;
			for (i = 0; i < begin.length; i++) {
				b[pos++] = (byte) begin[i];
			}
			for (i = 0; i < value.length; i++) {
				b[pos++] = value[i];
			}
			for (i = 0; i < end.length; i++) {
				b[pos++] = (byte) end[i];
			}

			return defineClass(name, b, 0, b.length);

		}

		static int count = 100000;

	}

	public static void main(String s[]) {
		final MemoryMonitor demo = new MemoryMonitor();
		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();
			}
		};
		JFrame f = new JFrame("MemoryMonitor");
		f.addWindowListener(l);
		f.getContentPane().add("Center", demo);
		f.pack();
		f.setSize(new Dimension(400, 500));
		f.setVisible(true);
		demo.surf.start();
		Thread thr = new Thread(new Memeater());
		thr.start();
	}

}

运行结果:

  • 大小: 90.4 KB
分享到:
评论
2 楼 surpassno 2016-03-03  
大写的牛逼
1 楼 skying007 2012-01-18  

相关推荐

    java可视化五子棋人人对弈

    在本项目"java可视化五子棋人人对弈"中,开发者使用Java编程语言构建了一个简单的双人对战五子棋游戏。以下是对该项目所涉及的关键知识点的详细解释: 1. **Java编程语言**:Java是一种跨平台、面向对象的编程语言...

    基于JAVA的可视化进程调度以及内存管理实验(附带实验报告)

    本程序有着优美的可视化界面(至少本人认为比网上其他的都好看),能动态显示内存条和内存分区表的变化。对JAVA初学者很友好,逻辑清晰,容易理解。本人为22级来自新疆大学的中南交换生,所以觉得下这个的大概率为...

    zookeeper可视化工具

    - **集群监控**:显示服务器状态,包括连接状态、会话信息、内存和磁盘使用情况等。 - **事件日志**:记录客户端的操作日志,便于追踪问题和调试。 - **警报系统**:设置阈值,当Zookeeper的状态达到预设条件时触发...

    Java写的可视化的阳历和农历

    在这个特定的项目中,我们关注的是一个使用Java实现的可视化工具,它能够显示阳历和农历。这个工具不仅能够帮助用户查询当前的农历日期,还能够查询过去或未来的任意年份的农历信息,对于需要了解农历的用户来说,...

    Hbase 可视化客户端工具(非phoenix连接)

    同时,它可能会实时显示HBase集群的状态,包括节点健康状况、内存使用情况、表和Region分布等,帮助管理员及时发现并解决问题。 对于数据分析,该工具可能还提供了高级查询功能,如过滤、聚合、排序等,甚至支持...

    MooInfo是OSHI 的一种可视化实现,用于查看有关系统和硬件的信息 如操作系统,进程,内存,CPU,磁盘,设备,传感器等

    2. **进程信息**:展示正在运行的进程列表,包括进程ID、名称、状态、CPU和内存使用情况等,这对于系统性能分析和故障排查很有帮助。 3. **内存状态**:提供总内存、已用内存、空闲内存等数据,以及内存分配和使用率...

    redis可视化工具

    6. **性能监控**:可视化工具通常会显示服务器的基本性能指标,如内存使用、CPU占用、命令执行速率等,帮助管理员监控系统状态。 7. **版本兼容性**:确保与不同版本的Redis兼容,适应不断更新的Redis生态。 关于...

    java gui可视化编程课程及实验指导中的所有练习

    在“赵老师java gui可视化编程中的所有实例以及实验指导中myqq的案例”这一课程中,你将深入学习如何利用Java的Swing和JavaFX库来构建美观、功能齐全的用户界面。下面,我们将详细探讨Java GUI编程的关键知识点,...

    jprofiler java内存监控

    4. **进行监控**:连接成功后,JProfiler将显示应用程序的内存、线程和CPU使用情况,用户可以开始进行分析。 5. **生成报告**:分析完成后,JProfiler可以导出分析结果为报告,方便后期查阅和分享。 ### Sn.txt...

    Redis可视化工具(纯净绿色版)

    1. 实时监控:工具可以实时显示Redis实例的内存使用情况、连接状态、命令执行频率等关键指标,帮助用户及时发现并解决性能问题。 2. 数据浏览与管理:用户可以通过图形界面查看和修改存储在Redis中的键值对,包括...

    Java ATM可视化存取款程序设计

    Java ATM可视化存取款程序设计是一项常见的编程实践项目,它要求开发者模拟银行自动取款机(ATM)的功能,提供用户交互界面,并处理各种金融交易。在这个项目中,学生需要运用Java编程语言来实现以下几个核心功能: ...

    rocketmq可视化jar包.zip

    1. **集群监控**:显示各个Broker节点的状态,包括CPU使用率、内存占用、网络I/O等关键指标,帮助管理员了解集群健康状况。 2. **主题与队列管理**:创建、修改和删除RocketMQ的主题(Topic)以及队列(Queue),...

    Redis-Desktop-Manager可视化管理工具.zip

    7. **监控与性能分析**:显示服务器的实时状态信息,如内存使用情况、CPU占用率等,帮助诊断和优化性能问题。 8. **安全性**:支持SSL加密连接,保证数据传输的安全性。 使用Redis Desktop Manager,开发人员可以更...

    zookeeper可视化窗口

    7. **性能指标**:显示Zookeeper服务器的CPU使用率、内存占用、网络I/O等性能指标,便于性能调优。 8. **报警设置**:设定阈值,当Zookeeper的某些状态或指标超出预设范围时,触发报警通知。 **zkui-master**:这...

    大数据可视化页面图表

    2. 数据预处理:使用Java或者Spark进行数据清洗、转换和聚合,确保数据适合可视化。 3. JSP页面设计:编写JSP页面,将处理后的数据传递给前端图表库,生成图表。 4. 用户交互:利用JavaScript实现图表的动态更新和...

    j2se 可视化操作,填写信息生成xml文件

    本主题聚焦于利用J2SE进行可视化操作,特别是涉及如何通过用户界面填写信息并生成XML文件。XML(eXtensible Markup Language)是一种结构化数据格式,广泛用于数据交换、配置文件以及存储轻量级数据。 首先,我们...

    java 在计算机内存中创建一个图像

    在Java编程语言中,创建和处理图像是一项常见的任务,特别是在图形用户界面(GUI)开发、游戏编程或数据可视化中。本篇文章将详细讲解如何在计算机内存中使用Java创建一个图像。 首先,Java提供了java.awt.image包...

    jdk6新强工具使用,触摸JAVA内存管理机制

    3. **jhat**:Java Heap Analysis Tool,与jmap配合使用,它可以分析由jmap生成的堆转储文件,提供一个基于HTTP/HTML的用户界面,以可视化的形式展示内存使用情况,便于找出可能的问题。 4. **jconsole**:这个工具...

Global site tag (gtag.js) - Google Analytics