1、 Java代码 1. package memoryManage; 2. 3. /* 4. * @(#)MemoryMonitor.java 1.3 05/11/17 5. * 6. * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved. 7. * 8. * Redistribution and use in source and binary forms, with or without 9. * modification, are perm
2、itted provided that the following conditions are met: 10. * 11. * -Redistribution of source code must retain the above copyright notice, this 12. * list of conditions and the following disclaimer. 13. * 14. * -Redistribution in binary form must reproduce the above copyright no
3、tice, 15. * this list of conditions and the following disclaimer in the documentation 16. * and/or other materials provided with the distribution. 17. * 18. * Neither the name of Sun Microsystems, Inc. or the names of contributors may 19. * be used to endorse or promote prod
4、ucts derived from this software without 20. * specific prior written permission. 21. * 22. * This software is provided "AS IS," without a warranty of any kind. ALL 23. * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING 24. * ANY IMPLIED WARRANTY OF MERC
5、HANTABILITY, FITNESS FOR A PARTICULAR PURPOSE 25. * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") 26. * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE 27. * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS 28.
6、 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST 29. * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, 30. * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY 31. * OF LIABILITY, ARISING OUT OF THE USE OF
7、OR INABILITY TO USE THIS SOFTWARE, 32. * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 33. * 34. * You acknowledge that this software is not designed, licensed or intended 35. * for use in the design, construction, operation or maintenance of any 36. * nuclea
8、r facility. 37. */ 38. 39. /* 40. * @(#)MemoryMonitor.java 1.3 05/11/17 41. */ 42. 43. import java.awt.*; 44. import java.awt.event.*; 45. import java.awt.image.BufferedImage; 46. import java.awt.geom.Line2D; 47. import java.awt.geom.Rectangle2D; 48. i
9、mport java.util.Date; 49. import javax.swing.*; 50. import javax.swing.border.EtchedBorder; 51. import javax.swing.border.TitledBorder; 52. import java.lang.management.*; 53. import java.util.*; 54. 55. /** 56. * Demo code which plots the memory usage by all memory po
10、ols. The memory usage 57. * is sampled at some time interval using java.lang.management API. This demo 58. * code is modified based java2d MemoryMonitor demo. 59. */ 60. class MemoryMonitor extends JPanel { 61. 62. static JCheckBox dateStampCB = new JCheckBox("Output Date
11、Stamp");
63. public Surface surf;
64. JPanel controls;
65. boolean doControls;
66. JTextField tf;
67. // Get memory pools.
68. static java.util.List
12、/ Total number of memory pools. 71. static int numPools = mpools.size(); 72. 73. public MemoryMonitor() { 74. setLayout(new BorderLayout()); 75. setBorder(new TitledBorder(new EtchedBorder(), "Memory Monitor")); 76. add(surf = new Surface());
13、 77. controls = new JPanel(); 78. controls.setPreferredSize(new Dimension(135, 80)); 79. Font font = new Font("serif", Font.PLAIN, 10); 80. JLabel label = new JLabel("Sample Rate"); 81. label.setFont(font); 82. label.setForeground
14、Color.red); 83. controls.add(label); 84. tf = new JTextField("1000"); 85. tf.setPreferredSize(new Dimension(45, 20)); 86. controls.add(tf); 87. controls.add(label = new JLabel("ms")); 88. label.setFont(font); 89. la
15、bel.setForeground(Color.red); 90. controls.add(dateStampCB); 91. dateStampCB.setFont(font); 92. addMouseListener(new MouseAdapter() { 93. public void mouseClicked(MouseEvent e) { 94. removeAll(); 95. if ((doC
16、ontrols = !doControls)) { 96. surf.stop(); 97. add(controls); 98. } else { 99. try { 100. surf.sleepAmount = Long.parseLong(tf.getText().trim()); 101. } cat
17、ch (Exception ex) { 102. } 103. surf.start(); 104. add(surf); 105. } 106. validate(); 107. repaint(); 108. } 109. }); 110. } 111
18、 112. public class Surface extends JPanel implements Runnable { 113. 114. public Thread thread; 115. public long sleepAmount = 1000; 116. public int usageHistCount = 20000; 117. private int w, h; 118. private BufferedImage bimg
19、 119. private Graphics2D big; 120. private Font font = new Font("Times New Roman", Font.PLAIN, 11); 121. private int columnInc; 122. private float usedMem[][]; 123. private int ptNum[]; 124. private int ascent, descent; 125
20、 private Rectangle graphOutlineRect = new Rectangle(); 126. private Rectangle2D mfRect = new Rectangle2D.Float(); 127. private Rectangle2D muRect = new Rectangle2D.Float(); 128. private Line2D graphLine = new Line2D.Float(); 129. private Color
21、 graphColor = new Color(46, 139, 87); 130. private Color mfColor = new Color(0, 100, 0); 131. private String usedStr; 132. 133. public Surface() { 134. setBackground(Color.black); 135. addMouseListener(new MouseAdapter() { 1
22、36. public void mouseClicked(MouseEvent e) { 137. if (thread == null) 138. start(); 139. else 140. stop(); 141. } 142. }); 143. i
23、nt i = 0; 144. usedMem = new float[numPools][]; 145. ptNum = new int[numPools]; 146. } 147. 148. public Dimension getMinimumSize() { 149. return getPreferredSize(); 150. } 151. 152. public Dimensi
24、on getMaximumSize() { 153. return getPreferredSize(); 154. } 155. 156. public Dimension getPreferredSize() { 157. return new Dimension(135, 80); 158. } 159. 160. public void paint(Graphics g) { 161. 162.
25、 if (big == null) { 163. return; 164. } 165. 166. big.setBackground(getBackground()); 167. big.clearRect(0, 0, w, h); 168. 169. h = h / ((numPools + numPools % 2) / 2); 170. w = w /
26、 2; 171. 172. int k = 0; // index of memory pool. 173. for (int i = 0; i < 2; i++) { 174. for (int j = 0; j < (numPools + numPools % 2) / 2; j++) { 175. plotMemoryUsage(w * i, h * j, w, h, k); 176.
27、 if (++k >= numPools) { 177. i = 3; 178. j = (numPools + numPools % 2) / 2; 179. break; 180. } 181. } 182. } 183. g.drawImage(bimg, 0, 0, t
28、his); 184. } 185. 186. public void plotMemoryUsage(int x1, int y1, int x2, int y2, int npool) { 187. 188. MemoryPoolMXBean mp = mpools.get(npool); 189. float usedMemory = mp.getUsage().getUsed(); 190. float totalMemory =
29、 mp.getUsage().getMax(); 191. 192. // .. Draw allocated and used strings .. 193. big.setColor(Color.green); 194. 195. // Print Max memory allocated for this memory pool. 196. big.drawString(String.valueOf((int) totalMemory / 102
30、4) + "K Max ", 197. x1 + 4.0f, (float) y1 + ascent + 0.5f); 198. big.setColor(Color.yellow); 199. 200. // Print the memory pool name. 201. big.drawString(mp.getName(), x1 + x2 / 2, (float) y1 + ascent 202.
31、 + 0.5f); 203. 204. // Print the memory used by this memory pool. 205. usedStr = String.valueOf((int) usedMemory / 1024) + "K used"; 206. big.setColor(Color.green); 207. big.drawString(usedStr, x1 + 4, y1 + y2 - descent); 2
32、08. 209. // Calculate remaining size 210. float ssH = ascent + descent; 211. float remainingHeight = (float) (y2 - (ssH * 2) - 0.5f); 212. float blockHeight = remainingHeight / 10; 213. float blockWidth = 20.0f; 214.
33、 float remainingWidth = (float) (x2 - blockWidth - 10); 215. 216. // .. Memory Free .. 217. big.setColor(mfColor); 218. int MemUsage = (int) (((totalMemory - usedMemory) / totalMemory) * 10); 219. int i = 0; 220.
34、 for (; i < MemUsage; i++) { 221. mfRect.setRect(x1 + 5, (float) y1 + ssH + i * blockHeight, 222. blockWidth, (float) blockHeight - 1); 223. big.fill(mfRect); 224. } 225. 226. // .. Memory
35、 Used .. 227. big.setColor(Color.green); 228. for (; i < 10; i++) { 229. muRect.setRect(x1 + 5, (float) y1 + ssH + i * blockHeight, 230. blockWidth, (float) blockHeight - 1); 231. big.fill(muRect);
36、 232. } 233. 234. // .. Draw History Graph .. 235. if (remainingWidth <= 30) 236. remainingWidth = (float) 30; 237. if (remainingHeight <= ssH) 238. remainingHeight = (float) ssH; 239.
37、 big.setColor(graphColor); 240. int graphX = x1 + 30; 241. int graphY = y1 + (int) ssH; 242. int graphW = (int) remainingWidth; 243. int graphH = (int) remainingHeight; 244. 245. graphOutlineRect.setRect(graphX,
38、 graphY, graphW, graphH); 246. big.draw(graphOutlineRect); 247. 248. int graphRow = graphH / 10; 249. 250. // .. Draw row .. 251. for (int j = graphY; j <= graphH + graphY; j += graphRow) { 252. graphLine.set
39、Line(graphX, j, graphX + graphW, j); 253. big.draw(graphLine); 254. } 255. 256. // .. Draw animated column movement .. 257. int graphColumn = graphW / 15; 258. 259. if (columnInc == 0) { 260.
40、 columnInc = graphColumn; 261. } 262. 263. for (int j = graphX + columnInc; j < graphW + graphX; j += graphColumn) { 264. graphLine.setLine(j, graphY, j, graphY + graphH); 265. big.draw(graphLine); 266. }
41、 267. 268. --columnInc; 269. 270. // Plot memory usage by this memory pool. 271. if (usedMem[npool] == null) { 272. usedMem[npool] = new float[usageHistCount]; 273. ptNum[npool] = 0; 274. }
42、 275. 276. // save memory usage history. 277. usedMem[npool][ptNum[npool]] = usedMemory; 278. 279. big.setColor(Color.yellow); 280. 281. int w1; // width of memory usage history. 282. if (ptNum[npool] > graph
43、W) { 283. w1 = graphW; 284. } else { 285. w1 = ptNum[npool]; 286. } 287. 288. for (int j = graphX + graphW - w1, k = ptNum[npool] - w1; k < ptNum[npool]; k++, j++) { 289. if (k != 0) {
44、 290. if (usedMem[npool][k] != usedMem[npool][k - 1]) { 291. int h1 = (int) (graphY + graphH 292. * ((totalMemory - usedMem[npool][k - 1]) / totalMemory)); 293. int h2 = (int) (graphY + gr
45、aphH 294. * ((totalMemory - usedMem[npool][k]) / totalMemory)); 295. big.drawLine(j - 1, h1, j, h2); 296. } else { 297. int h1 = (int) (graphY + graphH 298.
46、 * ((totalMemory - usedMem[npool][k]) / totalMemory)); 299. big.fillRect(j, h1, 1, 1); 300. } 301. } 302. } 303. if (ptNum[npool] + 2 == usedMem[npool].length) { 304. /
47、/ throw out oldest point 305. for (int j = 1; j < ptNum[npool]; j++) { 306. usedMem[npool][j - 1] = usedMem[npool][j]; 307. } 308. --ptNum[npool]; 309. } else { 310. ptNum[npool]++
48、 311. } 312. } 313. 314. public void start() { 315. thread = new Thread(this); 316. thread.setPriority(Thread.MIN_PRIORITY); 317. thread.setName("MemoryMonitor"); 318. thread.start(); 319
49、 } 320. 321. public synchronized void stop() { 322. thread = null; 323. notify(); 324. } 325. 326. public void run() { 327. 328. Thread me = Thread.currentThread(); 329. 330.
50、while (thread == me && !isShowing() || getSize().width == 0) { 331. try { 332. thread.sleep(500); 333. } catch (InterruptedException e) { 334. return; 335. } 336. } 337.






