1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.giraph.utils;
20
21 import java.io.BufferedReader;
22 import java.io.IOException;
23 import java.io.InputStreamReader;
24 import java.io.PrintStream;
25 import java.lang.management.ManagementFactory;
26 import java.nio.charset.Charset;
27 import java.util.Date;
28
29
30
31
32 public class JMap {
33
34 public static final String ARGS = " -histo ";
35
36 private static String LIVE_HISTO_OPTION = " -histo:live ";
37
38
39 protected JMap() { }
40
41
42
43
44
45
46 public static int getProcessId() {
47 String processId = ManagementFactory.getRuntimeMXBean().getName();
48 if (processId.contains("@")) {
49 processId = processId.substring(0, processId.indexOf("@"));
50 }
51 return Integer.parseInt(processId);
52 }
53
54
55
56
57
58
59
60
61 public static void heapHistogramDump(int numLines,
62 boolean liveObjectsOnly,
63 String jmapPath) {
64 heapHistogramDump(numLines, liveObjectsOnly, System.err, jmapPath);
65 }
66
67
68
69
70
71
72
73 public static void heapHistogramDump(int numLines, String jmapPath) {
74 heapHistogramDump(numLines, System.err, jmapPath);
75 }
76
77
78
79
80
81
82
83
84 public static void heapHistogramDump(int numLines, PrintStream printStream,
85 String jmapPath) {
86 heapHistogramDump(numLines, false, printStream, jmapPath);
87 }
88
89
90
91
92
93
94
95
96
97 private static void heapHistogramDump(int numLines,
98 boolean liveObjectsOnly,
99 PrintStream printStream,
100 String jmapPath) {
101 try {
102 String args = liveObjectsOnly ? LIVE_HISTO_OPTION : ARGS;
103 Process p = Runtime.getRuntime().exec(jmapPath + args + getProcessId());
104 BufferedReader in = new BufferedReader(
105 new InputStreamReader(p.getInputStream(), Charset.defaultCharset()));
106 printStream.println("JMap " +
107 (liveObjectsOnly ? "histo:live" : "histo") +
108 " dump at " + new Date());
109 String line = in.readLine();
110 for (int i = 0; i < numLines && line != null; ++i) {
111 printStream.println("--\t" + line);
112 line = in.readLine();
113 }
114 in.close();
115 } catch (IOException e) {
116 e.printStackTrace();
117 }
118 }
119 }