1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.hadoop.hbase.util;
19
20 import java.lang.reflect.Field;
21 import java.lang.reflect.Method;
22 import java.nio.ByteOrder;
23 import java.security.AccessController;
24 import java.security.PrivilegedAction;
25
26 import org.apache.commons.logging.Log;
27 import org.apache.commons.logging.LogFactory;
28 import org.apache.hadoop.hbase.classification.InterfaceAudience;
29 import org.apache.hadoop.hbase.classification.InterfaceStability;
30
31 import sun.misc.Unsafe;
32
33 @InterfaceAudience.Private
34 @InterfaceStability.Evolving
35 @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="REC_CATCH_EXCEPTION",
36 justification="If exception, presume unaligned")
37 public final class UnsafeAccess {
38
39 private static final Log LOG = LogFactory.getLog(UnsafeAccess.class);
40
41 public static final Unsafe theUnsafe;
42
43
44 public static final int BYTE_ARRAY_BASE_OFFSET;
45 private static boolean unaligned = false;
46
47 static {
48 theUnsafe = (Unsafe) AccessController.doPrivileged(new PrivilegedAction<Object>() {
49 @Override
50 public Object run() {
51 try {
52 Field f = Unsafe.class.getDeclaredField("theUnsafe");
53 f.setAccessible(true);
54 return f.get(null);
55 } catch (Throwable e) {
56 LOG.warn("sun.misc.Unsafe is not accessible", e);
57 }
58 return null;
59 }
60 });
61
62 if(theUnsafe != null){
63 BYTE_ARRAY_BASE_OFFSET = theUnsafe.arrayBaseOffset(byte[].class);
64 try {
65
66 Class<?> clazz = Class.forName("java.nio.Bits");
67 Method m = clazz.getDeclaredMethod("unaligned");
68 m.setAccessible(true);
69 unaligned = (boolean) m.invoke(null);
70 } catch (Exception e) {
71 unaligned = false;
72 }
73 } else{
74 BYTE_ARRAY_BASE_OFFSET = -1;
75 }
76 }
77
78 private UnsafeAccess(){}
79
80 public static boolean isAvailable() {
81 return theUnsafe != null;
82 }
83
84
85
86
87
88 public static boolean unaligned() {
89 return unaligned;
90 }
91
92 public static final boolean littleEndian = ByteOrder.nativeOrder()
93 .equals(ByteOrder.LITTLE_ENDIAN);
94 }