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