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 public final class UnsafeAccess {
36
37 private static final Log LOG = LogFactory.getLog(UnsafeAccess.class);
38
39 public static final Unsafe theUnsafe;
40
41
42 public static final int BYTE_ARRAY_BASE_OFFSET;
43 private static boolean unaligned = false;
44
45 static {
46 theUnsafe = (Unsafe) AccessController.doPrivileged(new PrivilegedAction<Object>() {
47 @Override
48 public Object run() {
49 try {
50 Field f = Unsafe.class.getDeclaredField("theUnsafe");
51 f.setAccessible(true);
52 return f.get(null);
53 } catch (Throwable e) {
54 LOG.warn("sun.misc.Unsafe is not accessible", e);
55 }
56 return null;
57 }
58 });
59
60 if(theUnsafe != null){
61 BYTE_ARRAY_BASE_OFFSET = theUnsafe.arrayBaseOffset(byte[].class);
62 try {
63
64 Class<?> clazz = Class.forName("java.nio.Bits");
65 Method m = clazz.getDeclaredMethod("unaligned");
66 m.setAccessible(true);
67 unaligned = (boolean) m.invoke(null);
68 } catch (Exception e) {
69 unaligned = false;
70 }
71 } else{
72 BYTE_ARRAY_BASE_OFFSET = -1;
73 }
74 }
75
76 private UnsafeAccess(){}
77
78 public static boolean isAvailable() {
79 return theUnsafe != null;
80 }
81
82
83
84
85
86 public static boolean unaligned() {
87 return unaligned;
88 }
89
90 public static final boolean littleEndian = ByteOrder.nativeOrder()
91 .equals(ByteOrder.LITTLE_ENDIAN);
92 }