1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.hadoop.hbase.util;
21
22 import java.lang.management.ManagementFactory;
23 import java.lang.management.RuntimeMXBean;
24 import java.lang.reflect.InvocationTargetException;
25 import java.lang.reflect.Method;
26 import java.nio.ByteBuffer;
27 import java.util.List;
28
29 import org.apache.hadoop.classification.InterfaceAudience;
30 import org.apache.hadoop.classification.InterfaceStability;
31
32 import com.google.common.base.Preconditions;
33
34 @InterfaceAudience.Private
35 @InterfaceStability.Evolving
36 public class DirectMemoryUtils {
37
38
39
40
41
42 public static long getDirectMemorySize() {
43 RuntimeMXBean RuntimemxBean = ManagementFactory.getRuntimeMXBean();
44 List<String> arguments = RuntimemxBean.getInputArguments();
45 long multiplier = 1;
46 for (String s : arguments) {
47 if (s.contains("-XX:MaxDirectMemorySize=")) {
48 String memSize = s.toLowerCase()
49 .replace("-xx:maxdirectmemorysize=", "").trim();
50
51 if (memSize.contains("k")) {
52 multiplier = 1024;
53 }
54
55 else if (memSize.contains("m")) {
56 multiplier = 1048576;
57 }
58
59 else if (memSize.contains("g")) {
60 multiplier = 1073741824;
61 }
62 memSize = memSize.replaceAll("[^\\d]", "");
63
64 long retValue = Long.parseLong(memSize);
65 return retValue * multiplier;
66 }
67
68 }
69 return 0;
70 }
71
72
73
74
75
76
77
78
79
80
81
82
83
84 public static void destroyDirectByteBuffer(ByteBuffer toBeDestroyed)
85 throws IllegalArgumentException, IllegalAccessException,
86 InvocationTargetException, SecurityException, NoSuchMethodException {
87
88 Preconditions.checkArgument(toBeDestroyed.isDirect(),
89 "toBeDestroyed isn't direct!");
90
91 Method cleanerMethod = toBeDestroyed.getClass().getMethod("cleaner");
92 cleanerMethod.setAccessible(true);
93 Object cleaner = cleanerMethod.invoke(toBeDestroyed);
94 Method cleanMethod = cleaner.getClass().getMethod("clean");
95 cleanMethod.setAccessible(true);
96 cleanMethod.invoke(cleaner);
97
98 }
99 }