All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.netty.util.internal.shaded.org.jctools.util.UnsafeAccess Maven / Gradle / Ivy

There is a newer version: 5.0.0.Alpha2
Show newest version
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.netty.util.internal.shaded.org.jctools.util;

import sun.misc.Unsafe;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

/**
 * Why should we resort to using Unsafe?
*
    *
  1. To construct class fields which allow volatile/ordered/plain access: This requirement is covered by * {@link AtomicReferenceFieldUpdater} and similar but their performance is arguably worse than the DIY approach * (depending on JVM version) while Unsafe intrinsification is a far lesser challenge for JIT compilers. *
  2. To construct flavors of {@link AtomicReferenceArray}. *
  3. Other use cases exist but are not present in this library yet. *
* * @author nitsanw */ @InternalAPI public class UnsafeAccess { public static final boolean SUPPORTS_GET_AND_SET; public static final Unsafe UNSAFE; static { Unsafe instance; try { final Field field = Unsafe.class.getDeclaredField("theUnsafe"); field.setAccessible(true); instance = (Unsafe) field.get(null); } catch (Exception ignored) { // Some platforms, notably Android, might not have a sun.misc.Unsafe // implementation with a private `theUnsafe` static instance. In this // case we can try and call the default constructor, which proves // sufficient for Android usage. try { Constructor c = Unsafe.class.getDeclaredConstructor(); c.setAccessible(true); instance = c.newInstance(); } catch (Exception e) { SUPPORTS_GET_AND_SET = false; throw new RuntimeException(e); } } boolean getAndSetSupport = false; try { Unsafe.class.getMethod("getAndSetObject", Object.class, Long.TYPE, Object.class); getAndSetSupport = true; } catch (Exception ignored) { } UNSAFE = instance; SUPPORTS_GET_AND_SET = getAndSetSupport; } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy