前几天我偶然发现了一个不安全的包装,它的功能让我感到惊讶。

当然,这个类是没有记录的,但是我想知道是否有一个很好的理由使用它。可能会出现哪些需要使用它的场景?如何在现实场景中使用它?

此外,如果您确实需要它,这难道不表明您的设计可能存在问题吗?

为什么Java包含这个类?


当前回答

我们使用Unsafe实现了数组、HashMaps、TreeMaps等大型集合。为了避免/最小化碎片,我们使用dlmalloc over unsafe的概念实现内存分配器。这帮助我们获得了并发性方面的性能。

其他回答

我们使用Unsafe实现了数组、HashMaps、TreeMaps等大型集合。为了避免/最小化碎片,我们使用dlmalloc over unsafe的概念实现内存分配器。这帮助我们获得了并发性方面的性能。

为了有效地复制内存(至少对于短块,复制速度比System.arraycopy()快);由Java LZF和Snappy编解码器使用。它们使用'getLong'和'putLong',这比逐字节复制要快;在复制16/32/64字节块时尤其有效。

我自己没有使用过它,但我认为如果你有一个变量,只是偶尔被多个线程读取(所以你真的不想让它volatile),你可以在主线程中写入它时使用putObjectVolatile,在从其他线程中进行罕见的读取时使用readObjectVolatile。

I was recently working on reimplementing the JVM and found that a surprising number of classes are implemented in terms of Unsafe. The class is mostly designed for the Java library implementers and contains features that are fundamentally unsafe but necessary for building fast primitives. For example, there are methods for getting and writing raw field offsets, using hardware-level synchronization, allocating and freeing memory, etc. It is not intended to be used by normal Java programmers; it's undocumented, implementation-specific, and inherently unsafe (hence the name!). Moreover, I think that the SecurityManager will disallow access to it in almost all cases.

简而言之,它的存在主要是为了允许库实现者访问底层机器,而不必在某些类(如AtomicInteger native)中声明每个方法。在常规Java编程中不需要使用或担心它,因为重点是使其余的库足够快,从而不需要这种访问。

不安全的。允许抛出检查异常而不声明它们。

这在处理反射或AOP的某些情况下非常有用。

假设您为用户定义的接口构建了通用代理。在特殊情况下,用户可以通过在接口中声明异常来指定由实现抛出的异常。这是我所知道的唯一方法,在接口的动态实现中引发一个受控异常。

import org.junit.Test;
/** need to allow forbidden references! */ import sun.misc.Unsafe;

/**
 * Demonstrate how to throw an undeclared checked exception.
 * This is a hack, because it uses the forbidden Class {@link sun.misc.Unsafe}.
 */
public class ExceptionTest {

    /**
     * A checked exception.
     */
    public static class MyException extends Exception {
        private static final long serialVersionUID = 5960664994726581924L;
    }

    /**
     * Throw the Exception.
     */
    @SuppressWarnings("restriction")
    public static void throwUndeclared() {
        getUnsafe().throwException(new MyException());
    }

    /**
     * Return an instance of {@link sun.misc.Unsafe}.
     * @return THE instance
     */
    @SuppressWarnings("restriction")
    private static Unsafe getUnsafe() {
        try {

            Field singleoneInstanceField = Unsafe.class.getDeclaredField("theUnsafe");
            singleoneInstanceField.setAccessible(true);
            return (Unsafe) singleoneInstanceField.get(null);

        } catch (IllegalArgumentException e) {
            throw createExceptionForObtainingUnsafe(e);
        } catch (SecurityException e) {
            throw createExceptionForObtainingUnsafe(e);
        } catch (NoSuchFieldException e) {
            throw createExceptionForObtainingUnsafe(e);
        } catch (IllegalAccessException e) {
            throw createExceptionForObtainingUnsafe(e);
        }
    }

    private static RuntimeException createExceptionForObtainingUnsafe(final Throwable cause) {
        return new RuntimeException("error while obtaining sun.misc.Unsafe", cause);
    }


    /**
     * scenario: test that an CheckedException {@link MyException} can be thrown
     * from an method that not declare it.
     */
    @Test(expected = MyException.class)
    public void testUnsingUnsaveToThrowCheckedException() {
        throwUndeclared();
    }
}