2.2. Unsafe APIThe Unsafe API is extremely efficient due to its addressing model. However, as the name suggests, this API is unsafe and has several drawbacks:- It often allows the Java programs to crash the JVM due to illegal memory usage
- It's a non-standard Java API
constuctor
Örnek
Şöyle yaparız
Field f = Unsafe.class.getDeclaredField("theUnsafe");f.setAccessible(true);Unsafe unsafe = (Unsafe) f.get(null);
allocateInstance metodu
Nesne için sadece bellek ayırır ve constructor'ı çağırmaz.
Örnek
Şöyle yaparız
class InitializationOrdering { private long a; public InitializationOrdering() { this.a = 1; } public long getA() { return this.a; } } InitializationOrdering o3 = (InitializationOrdering) unsafe.allocateInstance(InitializationOrdering.class); assertEquals(o3.getA(), 0);
defineAnonymousClass metodu
Java 15 ile Bunun yerine artık Hidden Classes kullanılıyor
getLong metodu
Örnek
Şöyle yaparız
public class Foo { private static final long OFFSET_value; private static final Unsafe UNSAFE = UnsafeLocator.UNSAFE; static { try { OFFSET_value = getOffset("value"); } catch (ReflectiveOperationException e) { ... } } private static long getOffset(String fieldName) throws NoSuchFieldException { Field field = Foo.class.getDeclaredField(fieldName); return UnsafeLocator.UNSAFE.objectFieldOffset(field); } public volatile long value; public long unsafe() { return UNSAFE.getLong(this, OFFSET_value); } }
Hiç yorum yok:
Yorum Gönder