View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.util;
19  
20  import java.lang.reflect.Field;
21  import java.nio.ByteOrder;
22  import java.security.AccessController;
23  import java.security.PrivilegedAction;
24  
25  import org.apache.commons.logging.Log;
26  import org.apache.commons.logging.LogFactory;
27  import org.apache.hadoop.hbase.classification.InterfaceAudience;
28  import org.apache.hadoop.hbase.classification.InterfaceStability;
29  
30  import sun.misc.Unsafe;
31  
32  @InterfaceAudience.Private
33  @InterfaceStability.Evolving
34  @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="REC_CATCH_EXCEPTION",
35    justification="If exception, presume unaligned")
36  public final class UnsafeAccess {
37  
38    private static final Log LOG = LogFactory.getLog(UnsafeAccess.class);
39  
40    public static final Unsafe theUnsafe;
41  
42    /** The offset to the first element in a byte array. */
43    public static final int BYTE_ARRAY_BASE_OFFSET;
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      } else{
63        BYTE_ARRAY_BASE_OFFSET = -1;
64      }
65    }
66  
67    private UnsafeAccess(){}
68  
69    public static final boolean littleEndian = ByteOrder.nativeOrder()
70        .equals(ByteOrder.LITTLE_ENDIAN);
71  }