SlideShare ist ein Scribd-Unternehmen logo
1 von 57
Do we need Unsafe in Java?
Andrei Pangin
andrey.pangin@corp.mail.ru
Mystic sun.misc.Unsafe
3
Can I override object with sun.misc.Unsafe?
Is there a way to force unload a class
by using the sun.misc.Unsafe class?
Can one break a security manager with sun.misc.Unsafe?
Rescuing a swallowed Exception in Java
How to free memory using Java Unsafe, using a Java reference?
Create a mutable java.lang.String
Mystic sun.misc.Unsafe
4 Mystic sun.misc.Unsafe
How to free memory using Java Unsafe, using a Java reference?
Player p = (Player) unsafe.allocateInstance(Player.class);
// Is there a way of accessing the memory address
// from the object reference
unsafe.freeMemory(p.hashCode());
http://stackoverflow.com/questions/24429777
5 Mystic sun.misc.Unsafe
Why it is called Unsafe
#
# A fatal error has been detected by the Java Runtime Environment:
#
# SIGSEGV (0xb) at pc=0x00002ad221034ee5, pid=3680, tid=1091057984
#
# JRE version: Java(TM) SE Runtime Environment (8.0_60-b27) (build 1.8.0_60-b27)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.60-b23 mixed mode linux-amd64)
# Problematic frame:
# C [libc.so.6+0x6dee5] cfree+0x25
#
# An error report file with more information is saved as:
# /home/apangin/hs_err_pid3680.log
#
6
What is Unsafe actually
• Bridge between Class Library and JVM
• For use inside JDK
- NIO
- AWT
- Reflection
- java.util.concurrent
- MethodHandles
• Exists in many JVMs, even on Android
Mystic sun.misc.Unsafe
7 Mystic sun.misc.Unsafe
public final class Unsafe {
static {
registerNatives();
sun.reflect.Reflection.registerMethodsToFilter(Unsafe.class, "getUnsafe");
}
private Unsafe() {}
private static final Unsafe theUnsafe = new Unsafe();
@CallerSensitive
public static Unsafe getUnsafe() {
Class cc = Reflection.getCallerClass();
if (cc.getClassLoader() != null)
throw new SecurityException("Unsafe");
return theUnsafe;
}
8 Mystic sun.misc.Unsafe
Getting Unsafe
public static Unsafe getUnsafe() throws Exception {
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
return (Unsafe) f.get(null);
}
9
Security hole?
Security Manager is off by default
$ java -Djava.security.manager
java.security.AccessControlException:
access denied
("java.lang.RuntimePermission"
"accessClassInPackage.sun.misc")
Mystic sun.misc.Unsafe
10 Mystic sun.misc.Unsafe
You’ve been warned!
$ javac Test.java
Test.java:2: warning: Unsafe is internal proprietary API and may
be removed in a future release
import sun.misc.Unsafe;
^
$ javac -XDignore.symbol.file Test.java
Inside Unsafe
12 Inside Unsafe
public native long allocateMemory(long bytes);
public native long reallocateMemory(long address, long bytes);
public native void freeMemory(long address);
public native byte getByte(long address);
public native void putByte(long address, byte x);
public native int getInt(Object o, long offset);
public native void putInt(Object o, long offset, int x);
public native long objectFieldOffset(Field f);
public native long staticFieldOffset(Field f);
public native int arrayBaseOffset(Class<?> arrayClass);
public native void copyMemory(Object srcBase, long srcOffset,
Object destBase, long destOffset,
long bytes);
13
package snow.misc;
public class MyUnsafe {
public native int getInt(long address);
#include <jni.h>
JNIEXPORT jint JNICALL
Java_snow_misc_MyUnsafe(JNIEnv* env, jobject myUnsafe, jlong address) {
return *(jint*)address;
}
Inside Unsafe
14 Inside Unsafe
JNI call
1. Create stack frame
2. Move arguments according to ABI
3. Wrap objects into JNI handles
4. Obtain JNIEnv* and jclass
5. Trace method_entry
6. Lock if synchronized
7. Lazy lookup and linking
8. in_java  in_native thread transition
9. Call the native function
10. Check for safepoint
11. Switch state to in_java
12. Unlock if synchronized
13. Notify method_exit
14. Unwrap result, reset JNI handles block
15. Handle exceptions
16. Remove stack frame
15
Implementation
• Most methods are JVM intrinsics
- E.g. getInt is a single MOV instruction
• Executed in Java or VM context
- Beware of mapped I/O
(safepoint pauses)
Inside Unsafe
16
public native int getIntVolatile(Object o, long offset);
public native void putIntVolatile(Object o, long offset, int x);
public native void putOrderedInt(Object o, long offset, int x);
public final native boolean compareAndSwapInt(Object o, long offset,
int expected, int x);
/* @since 1.8 */
public native void loadFence();
public native void storeFence();
public native void fullFence();
public final int getAndAddInt(Object o, long offset, int delta) {
int v;
do {
v = getIntVolatile(o, offset);
} while (!compareAndSwapInt(o, offset, v, v + delta));
return v;
}
Inside Unsafe
17
i.getAndAdd(5)
lock addl $0x5,0xc(%r10)loop:
mov 0xc(%r10),%eax
mov %eax,%r11d
add $0x5,%r11d
lock cmpxchg %r11d,0xc(%r10)
sete %r11b
movzbl %r11b,%r11d
test %r11d,%r11d
je loop
JDK 7u72 -XX:+PrintAssembly JDK 8u60
83
46
15 11
132
105
45 43
1 2 3 4
ops/μs
threads
Inside Unsafe
18 Inside Unsafe
public native Class<?> defineClass(String name, byte[] b, int off, int len,
ClassLoader loader,
ProtectionDomain protectionDomain);
public native Class<?> defineAnonymousClass(Class<?> hostClass, byte[] data,
Object[] cpPatches);
public native Object allocateInstance(Class<?> cls) throws InstantiationException;
public native void park(boolean isAbsolute, long time);
public native void unpark(Object thread);
public native int getLoadAverage(double[] loadavg, int nelems);
public native void throwException(Throwable ee);
19 Inside Unsafe
Deprecated in JDK 8, removed in 9
@Deprecated
public native void monitorEnter(Object o);
@Deprecated
public native void monitorExit(Object o);
@Deprecated
public native boolean tryMonitorEnter(Object o);
// Phantom HotSpot intrinsics
public native void prefetchRead(Object o, long offset);
public native void prefetchWrite(Object o, long offset);
Use cases
21
Off-heap collections
• Lists, sets, maps
- Large capacity > 2 GB
- Predictable GC pauses
- No heap fragmentation (CMS Promotion Failures)
- Data locality
Use cases
22
Data locality
Key
Value
Key
Value
Map.Entry Off-heap layout
a b c a b c a b c
Use cases
23 Use cases
Off-heap hash map
0 addr 0 … addr 0
hash time next
key (?)
value
hash time 0
key (?)
value
entry
one.nio.mem.SharedMemoryMap
24 OffheapLongList
public OffheapLongList(int initialCapacity) {
capacity = Math.max(initialCapacity, 4);
base = unsafe.allocateMemory(capacity * 8L);
}
public void add(long value) {
if (size >= capacity) {
capacity *= 2;
base = unsafe.reallocateMemory(base, capacity * 8L);
}
unsafe.putLong(base + size * 8L, value);
size++;
}
public long get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
return unsafe.getLong(base + index * 8L);
}
25 Use cases
When to free memory?
class OffheapCleaner<T> extends PhantomReference<T> {
static final ReferenceQueue<T> queue = new ReferenceQueue<T>();
final long address;
OffheapCleaner(T referent, long address) {
super(referent, queue);
this.address = address;
}
}
while (true) {
OffheapCleaner<T> cleaner = (OffheapCleaner<T>) queue.remove();
unsafe.freeMemory(cleaner.address);
}
26
Why not ByteBuffers?
• Size limit (Integer.MAX_VALUE)
• Not thread-safe
• No freeMemory
public void forceClean(ByteBuffer buffer) {
((sun.nio.ch.DirectBuffer) buffer)).cleaner().clean();
}
Use cases
27 sun.nio.ch.FileChannelImpl
try {
// If no exception was thrown from map0, the address is valid
addr = map0(imode, mapPosition, mapSize);
} catch (OutOfMemoryError x) {
// An OutOfMemoryError may indicate that we've exhausted memory
// so force gc and re-attempt map
System.gc();
try {
Thread.sleep(100);
} catch (InterruptedException y) {
Thread.currentThread().interrupt();
}
try {
addr = map0(imode, mapPosition, mapSize);
} catch (OutOfMemoryError y) {
// After a second OOME, fail
throw new IOException("Map failed", y);
}
}
28 Cassandra
// Hoping GC will remove some not used tables.
System.gc();
Thread.sleep(60000);
location = estimateFlushPath();
if (location!=null)
return new File(location, ssTableFileName).getAbsolutePath();
// Hoping GC will remove some not used tables - sometimes 2 GC cycles are needed.
logger_.warn("Still Insufficient disk space to flush "+ssTableFileName);
System.gc();
Thread.sleep(60000);
location = estimateFlushPath();
29 Use cases
Direct buffers ↔ Unsafe
Field addressField = Buffer.class.getDeclaredField("address");
addressField.setAccessible(true);
// ByteBuffer  address
long address = addressField.getLong(byteBuffer);
// address  ByteBuffer
ByteBuffer result = prototype.duplicate();
addressField.setLong(result, address);
30 Use cases
Benchmark
Benchmark Mode Cnt Score Error Units
b.byteBuffer thrpt 15 290,832 ± 7,858 ops/us
b.rawMemory thrpt 15 480,799 ± 2,610 ops/us
public void byteBuffer() {
buf.putLong(0, order.timestamp);
buf.put(8, order.operationType);
buf.putInt(9, order.productId);
buf.putFloat(13, order.price);
}
public void rawMemory() {
unsafe.putLong(addr + 0, order.timestamp);
unsafe.put(addr + 8, order.operationType);
unsafe.putInt(addr + 9, order.productId);
unsafe.putFloat(addr + 13, order.price);
}
31
I/O and persistence
• Persistent caches and storages
- Memory-mapped files (64-bit)
- Shared memory
• Cooperation with OS
- Pointer arithmetic, alignment
- mlock, madvise etc.
Use cases
32 Use cases
Mapping large files
// Mapping
Method map0 = FileChannelImpl.class.getDeclaredMethod(
"map0", int.class, long.class, long.class);
map0.setAccessible(true);
long addr = (Long) map0.invoke(f.getChannel(), 1, 0L, f.length());
// Unmapping
Method unmap0 = FileChannelImpl.class.getDeclaredMethod(
"unmap0", long.class, long.class);
unmap0.setAccessible(true);
unmap0.invoke(null, addr, length);
33
IPC, Messaging
• Concurrent off-heap buffers and queues
• High-performance messaging
- Disruptor
- Aeron: 6M msg/s
• Shared data structures
- Chronicle Map
Use cases
34 Use cases
Coding / Decoding
do {
v1 += getInt(buf, offset) * P2;
v1 = ((v1 << 13) | (v1 >>> 19)) * P1;
v2 += getInt(buf, offset + 4) * P2;
v2 = ((v2 << 13) | (v2 >>> 19)) * P1;
v3 += getInt(buf, offset + 8) * P2;
v3 = ((v3 << 13) | (v3 >>> 19)) * P1;
v4 += getInt(buf, offset + 12) * P2;
v4 = ((v4 << 13) | (v4 >>> 19)) * P1;
} while ((offset += 16) <= limit);
public int getInt(byte[] buf, int off) {
return (buf[off] & 0xff) |
(buf[off + 1] & 0xff) << 8 |
(buf[off + 2] & 0xff) << 16 |
(buf[off + 3]) << 24;
}
public int getInt(byte[] buf, int off) {
return unsafe.getInt(buf,
byteArrayOffset + off);
}
xxHash loop
35 Use cases
Benchmark
Benchmark (length) Mode Cnt Score Error Units
b.xxhashArray 10 thrpt 5 61697,875 ± 849,565 ops/ms
b.xxhashArray 100 thrpt 5 13552,417 ± 91,039 ops/ms
b.xxhashArray 1000 thrpt 5 1749,843 ± 12,290 ops/ms
b.xxhashUnsafe 10 thrpt 5 77358,056 ± 675,536 ops/ms
b.xxhashUnsafe 100 thrpt 5 34153,796 ± 319,798 ops/ms
b.xxhashUnsafe 1000 thrpt 5 5259,813 ± 43,870 ops/ms
36
Serialization
• Fast conversion to/from byte[]
• Access private fields
- Reflection vs. Unsafe
• Instantiate objects without constructor
- unsafe.allocateInstance()
Use cases
37
one-nio serialization
• Extend sun.reflect.MagicAccessorImpl
- no bytecode verification
• Fast and compact
• Supports class evolution
- Java serialization
- JBoss
- Kryo
- Protobuf
Use cases
38
Native APIs
• Own network library
- Linux-specific TCP features and socket options
- Integration with OpenSSL
• I/O and memory management
- mlock
- posix_fadvise
• setuid
• sched_setaffinity
Use cases
Removal of sun.misc.Unsafe
40 Removal of sun.misc.Unsafe
An absolute disaster
Cassandra
Netty Guava
Hazelcast
Mockito
GWT
Hadoop
Zookeeper
Kafka
Gson
Neo4j
Grails
Spring
Disruptor
JRuby
Scala
Akka
41
Why?
Removal of sun.misc.Unsafe
Integrity and security
Maintenance costs
42
Chronology
• JEP 200: The Modular JDK
• Mark Reinhold speaks at Devoxx
• Chris Engelbert started a discussion group
• Apocalyptic post at blog.dripstat.com
• JCrete
• JVM Language Summit
• JEP 260: Encapsulate Most Internal APIs
Removal of sun.misc.Unsafe
2014 / 07
2015 / 06
2015 / 07
2015 / 08
43
Migration plan
• Replacement in JDK 8  hide in JDK 9
- sun.misc.BASE64Encoder etc.
- Available via command-line flag
• No replacement in JDK 8  available outside
- sun.misc.Unsafe, sun.reflect.ReflectionFactory
- sun.misc.Cleaner, sun.misc.SignalHandler
• Replacement in JDK 9  hide in JDK 9,
remove in JDK 10
Removal of sun.misc.Unsafe
Replacements
45
Project Panama
• JEP 191: Foreign Function Interface
• Expected in Java 10
• JNR
Replacements
public interface LibC {
int setuid(@uid_t long uid);
}
LibC libc = LibraryLoader.create(LibC.class).load("c");
libc.setuid(restrictedUser);
46
JEP 193: VarHandles
• Targeted for Java 9
Replacements
class Queue {
int size;
...
}
VarHandle queueSize = MethodHandles.lookup().
findVarHandle(Queue.class, "size", int.class);
queueSize.addAndGet(10);
47 Replacements
// Desired syntax
VarHandle queueSize = Queue::size;
VarHandle intElementHandle = MethodHandles.lookup()
.arrayElementVarHandle(int[].class);
VarHandle longArrayViewHandle = MethodHandles.lookup()
.arrayElementViewHandle(byte[].class, long[].class, true, false);
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(8);
VarHandle bufferView = MethodHandles.lookup()
.byteBufferViewVarHandle(long[].class, true, false);
48 Replacements
public static void fullFence();
public static void acquireFence()
public static void releaseFence();
public static void loadLoadFence();
public static void storeStoreFence();
• getRelaxed, getVolatile, getOpaque
• setRelaxed, setVolatile, setOpaque
• getAquire, setRelease
• compareAndSet, compareAndExchangeVolatile
• compareAndExchangeAcquire, compareAndExchangeRelease
• weakCompareAndSet, weakCompareAndSetAcquire, weakCompareAndSetRelease
• getAndSet, getAndAdd, addAndGet
49 Replacements
// Not in Java 9
MemoryRegion region = MemoryRegion.allocateNative(
"myname", MemoryRegion.UNALIGNED, Long.MAX_VALUE);
VarHandle regionView = region.asVarHandle(long[].class, true, false);
regionView.set(region, 0, Long.MAX_VALUE);
return regionView.get(region, 0);
50 Replacements
Serialization
ReflectionFactory reflectionFactory =
ReflectionFactory.getReflectionFactory();
Constructor<?> baseConstructor = Object.class.getDeclaredConstructor();
Constructor<?> constructor = reflectionFactory.
newConstructorForSerialization(Foo.class, baseConstructor);
return (Foo) constructor.newInstance();
jobject AllocObject(JNIEnv *env, jclass clazz); JNI
51 Replacements
Можно жить и без Unsafe
но грустно
Unsafe bugs
53 Unsafe bugs
JVM Bugs
#
# A fatal error has been detected by the Java Runtime Environment:
#
# SIGSEGV (0xb) at pc=0x00002b9fd9f44898, pid=19692, tid=1096575296
#
# JRE version: 6.0_24-b07
# Java VM: Java HotSpot(TM) 64-Bit Server VM (19.1-b02 mixed mode linux-amd64)
# Problematic frame:
# J Test.loop(Lsun/misc/Unsafe;J)V
#
# An error report file with more information is saved as:
# /home/apangin/hs_err_pid19692.log
#
# If you would like to submit a bug report, please visit:
# http://java.sun.com/webapps/bugreport/crash.jsp
#
for (int i = 0; i < BUF_SIZE; i += 8)
unsafe.putLong(addr + i,
Long.reverseBytes(i));
54
JVM Bugs
• JDK-6968348: Unsafe + Long.reverseBytes
• JDK-7196566: Reported by me 
• JDK-8022783: Non-public bug in C2
• JDK-8087134: Wrong C1 optimization
Unsafe bugs
6u25
7u40
7u71
8u60
-XX:-TieredCompilation
55 Unsafe bugs
Not yet fixed
RandomAccessFile raf = new RandomAccessFile("/dev/shm/cache.tmp", "rw");
raf.setLength(5_000_000_000L);
MappedByteBuffer buf = raf.getChannel().map(READ_WRITE, 0, raf.length());
for (int i = 0; i < 5000; i++) {
buf.put(new byte[1_000_000]);
}
SIGBUS
Thank you
@AndreiPangin
57
Development @ OK
• Blog
- http://habrahabr.ru/company/odnoklassniki
• Open source
- https://github.com/odnoklassniki
• Career
- http://v.ok.ru
Thank you

Weitere ähnliche Inhalte

Was ist angesagt?

アプリケーションを作るときに考える25のこと
アプリケーションを作るときに考える25のことアプリケーションを作るときに考える25のこと
アプリケーションを作るときに考える25のことTakafumi ONAKA
 
F#入門 ~関数プログラミングとは何か~
F#入門 ~関数プログラミングとは何か~F#入門 ~関数プログラミングとは何か~
F#入門 ~関数プログラミングとは何か~Nobuhisa Koizumi
 
Optimizing Apache Spark SQL Joins
Optimizing Apache Spark SQL JoinsOptimizing Apache Spark SQL Joins
Optimizing Apache Spark SQL JoinsDatabricks
 
Master Canary Forging: 新しいスタックカナリア回避手法の提案 by 小池 悠生 - CODE BLUE 2015
Master Canary Forging: 新しいスタックカナリア回避手法の提案 by 小池 悠生 - CODE BLUE 2015Master Canary Forging: 新しいスタックカナリア回避手法の提案 by 小池 悠生 - CODE BLUE 2015
Master Canary Forging: 新しいスタックカナリア回避手法の提案 by 小池 悠生 - CODE BLUE 2015CODE BLUE
 
Data Security at Scale through Spark and Parquet Encryption
Data Security at Scale through Spark and Parquet EncryptionData Security at Scale through Spark and Parquet Encryption
Data Security at Scale through Spark and Parquet EncryptionDatabricks
 
MySQLとPostgreSQLの基本的な実行プラン比較
MySQLとPostgreSQLの基本的な実行プラン比較MySQLとPostgreSQLの基本的な実行プラン比較
MySQLとPostgreSQLの基本的な実行プラン比較Shinya Sugiyama
 
カスタムメモリマネージャと高速なメモリアロケータについて
カスタムメモリマネージャと高速なメモリアロケータについてカスタムメモリマネージャと高速なメモリアロケータについて
カスタムメモリマネージャと高速なメモリアロケータについてalwei
 
SATySFi 最近の発展と目下実装中の変更
SATySFi 最近の発展と目下実装中の変更SATySFi 最近の発展と目下実装中の変更
SATySFi 最近の発展と目下実装中の変更T. Suwa
 
初心者がRSA暗号を教わったら自力でCTFの問題が解けるようになった話
初心者がRSA暗号を教わったら自力でCTFの問題が解けるようになった話初心者がRSA暗号を教わったら自力でCTFの問題が解けるようになった話
初心者がRSA暗号を教わったら自力でCTFの問題が解けるようになった話mariydi1
 
圏論のモナドとHaskellのモナド
圏論のモナドとHaskellのモナド圏論のモナドとHaskellのモナド
圏論のモナドとHaskellのモナドYoshihiro Mizoguchi
 
Visual C++で使えるC++11
Visual C++で使えるC++11Visual C++で使えるC++11
Visual C++で使えるC++11nekko1119
 
PHPでマルチスレッド
PHPでマルチスレッドPHPでマルチスレッド
PHPでマルチスレッドkarky7
 
[CB16] バイナリロックスターになる:Binary Ninjaによるプログラム解析入門 by Sophia D’Antoine
[CB16] バイナリロックスターになる:Binary Ninjaによるプログラム解析入門 by Sophia D’Antoine[CB16] バイナリロックスターになる:Binary Ninjaによるプログラム解析入門 by Sophia D’Antoine
[CB16] バイナリロックスターになる:Binary Ninjaによるプログラム解析入門 by Sophia D’AntoineCODE BLUE
 
RecSplit Minimal Perfect Hashing
RecSplit Minimal Perfect HashingRecSplit Minimal Perfect Hashing
RecSplit Minimal Perfect HashingThomas Mueller
 
Nginx Internals
Nginx InternalsNginx Internals
Nginx InternalsJoshua Zhu
 
初心者向けCTFのWeb分野の強化法
初心者向けCTFのWeb分野の強化法初心者向けCTFのWeb分野の強化法
初心者向けCTFのWeb分野の強化法kazkiti
 
Black Hat EU 2010 - Attacking Java Serialized Communication
Black Hat EU 2010 - Attacking Java Serialized CommunicationBlack Hat EU 2010 - Attacking Java Serialized Communication
Black Hat EU 2010 - Attacking Java Serialized Communicationmsaindane
 
TypeScript製フレームワーク「Nest」のご紹介
TypeScript製フレームワーク「Nest」のご紹介TypeScript製フレームワーク「Nest」のご紹介
TypeScript製フレームワーク「Nest」のご紹介bitbank, Inc. Tokyo, Japan
 
プログラムの処方箋~健康なコードと病んだコード
プログラムの処方箋~健康なコードと病んだコードプログラムの処方箋~健康なコードと病んだコード
プログラムの処方箋~健康なコードと病んだコードShigenori Sagawa
 
JavaScript難読化読経
JavaScript難読化読経JavaScript難読化読経
JavaScript難読化読経Yosuke HASEGAWA
 

Was ist angesagt? (20)

アプリケーションを作るときに考える25のこと
アプリケーションを作るときに考える25のことアプリケーションを作るときに考える25のこと
アプリケーションを作るときに考える25のこと
 
F#入門 ~関数プログラミングとは何か~
F#入門 ~関数プログラミングとは何か~F#入門 ~関数プログラミングとは何か~
F#入門 ~関数プログラミングとは何か~
 
Optimizing Apache Spark SQL Joins
Optimizing Apache Spark SQL JoinsOptimizing Apache Spark SQL Joins
Optimizing Apache Spark SQL Joins
 
Master Canary Forging: 新しいスタックカナリア回避手法の提案 by 小池 悠生 - CODE BLUE 2015
Master Canary Forging: 新しいスタックカナリア回避手法の提案 by 小池 悠生 - CODE BLUE 2015Master Canary Forging: 新しいスタックカナリア回避手法の提案 by 小池 悠生 - CODE BLUE 2015
Master Canary Forging: 新しいスタックカナリア回避手法の提案 by 小池 悠生 - CODE BLUE 2015
 
Data Security at Scale through Spark and Parquet Encryption
Data Security at Scale through Spark and Parquet EncryptionData Security at Scale through Spark and Parquet Encryption
Data Security at Scale through Spark and Parquet Encryption
 
MySQLとPostgreSQLの基本的な実行プラン比較
MySQLとPostgreSQLの基本的な実行プラン比較MySQLとPostgreSQLの基本的な実行プラン比較
MySQLとPostgreSQLの基本的な実行プラン比較
 
カスタムメモリマネージャと高速なメモリアロケータについて
カスタムメモリマネージャと高速なメモリアロケータについてカスタムメモリマネージャと高速なメモリアロケータについて
カスタムメモリマネージャと高速なメモリアロケータについて
 
SATySFi 最近の発展と目下実装中の変更
SATySFi 最近の発展と目下実装中の変更SATySFi 最近の発展と目下実装中の変更
SATySFi 最近の発展と目下実装中の変更
 
初心者がRSA暗号を教わったら自力でCTFの問題が解けるようになった話
初心者がRSA暗号を教わったら自力でCTFの問題が解けるようになった話初心者がRSA暗号を教わったら自力でCTFの問題が解けるようになった話
初心者がRSA暗号を教わったら自力でCTFの問題が解けるようになった話
 
圏論のモナドとHaskellのモナド
圏論のモナドとHaskellのモナド圏論のモナドとHaskellのモナド
圏論のモナドとHaskellのモナド
 
Visual C++で使えるC++11
Visual C++で使えるC++11Visual C++で使えるC++11
Visual C++で使えるC++11
 
PHPでマルチスレッド
PHPでマルチスレッドPHPでマルチスレッド
PHPでマルチスレッド
 
[CB16] バイナリロックスターになる:Binary Ninjaによるプログラム解析入門 by Sophia D’Antoine
[CB16] バイナリロックスターになる:Binary Ninjaによるプログラム解析入門 by Sophia D’Antoine[CB16] バイナリロックスターになる:Binary Ninjaによるプログラム解析入門 by Sophia D’Antoine
[CB16] バイナリロックスターになる:Binary Ninjaによるプログラム解析入門 by Sophia D’Antoine
 
RecSplit Minimal Perfect Hashing
RecSplit Minimal Perfect HashingRecSplit Minimal Perfect Hashing
RecSplit Minimal Perfect Hashing
 
Nginx Internals
Nginx InternalsNginx Internals
Nginx Internals
 
初心者向けCTFのWeb分野の強化法
初心者向けCTFのWeb分野の強化法初心者向けCTFのWeb分野の強化法
初心者向けCTFのWeb分野の強化法
 
Black Hat EU 2010 - Attacking Java Serialized Communication
Black Hat EU 2010 - Attacking Java Serialized CommunicationBlack Hat EU 2010 - Attacking Java Serialized Communication
Black Hat EU 2010 - Attacking Java Serialized Communication
 
TypeScript製フレームワーク「Nest」のご紹介
TypeScript製フレームワーク「Nest」のご紹介TypeScript製フレームワーク「Nest」のご紹介
TypeScript製フレームワーク「Nest」のご紹介
 
プログラムの処方箋~健康なコードと病んだコード
プログラムの処方箋~健康なコードと病んだコードプログラムの処方箋~健康なコードと病んだコード
プログラムの処方箋~健康なコードと病んだコード
 
JavaScript難読化読経
JavaScript難読化読経JavaScript難読化読経
JavaScript難読化読経
 

Ähnlich wie Do we need Unsafe in Java?

A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVMRafael Winterhalter
 
Java Questions
Java QuestionsJava Questions
Java Questionsbindur87
 
Security Meetup 22 октября. «PHP Unserialize Exploiting». Павел Топорков. Лаб...
Security Meetup 22 октября. «PHP Unserialize Exploiting». Павел Топорков. Лаб...Security Meetup 22 октября. «PHP Unserialize Exploiting». Павел Топорков. Лаб...
Security Meetup 22 октября. «PHP Unserialize Exploiting». Павел Топорков. Лаб...Mail.ru Group
 
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...Mail.ru Group
 
55 new things in Java 7 - Devoxx France
55 new things in Java 7 - Devoxx France55 new things in Java 7 - Devoxx France
55 new things in Java 7 - Devoxx FranceDavid Delabassee
 
JNI - Java & C in the same project
JNI - Java & C in the same projectJNI - Java & C in the same project
JNI - Java & C in the same projectKarol Wrótniak
 
The mighty js_function
The mighty js_functionThe mighty js_function
The mighty js_functiontimotheeg
 
The Anatomy of an Exploit
The Anatomy of an ExploitThe Anatomy of an Exploit
The Anatomy of an ExploitPatricia Aas
 
Exploitation of counter overflows in the Linux kernel
Exploitation of counter overflows in the Linux kernelExploitation of counter overflows in the Linux kernel
Exploitation of counter overflows in the Linux kernelVitaly Nikolenko
 
No dark magic - Byte code engineering in the real world
No dark magic - Byte code engineering in the real worldNo dark magic - Byte code engineering in the real world
No dark magic - Byte code engineering in the real worldtcurdt
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy PluginsPaul King
 
The Anatomy of an Exploit (NDC TechTown 2019)
The Anatomy of an Exploit (NDC TechTown 2019)The Anatomy of an Exploit (NDC TechTown 2019)
The Anatomy of an Exploit (NDC TechTown 2019)Patricia Aas
 
The Anatomy of an Exploit (NDC TechTown 2019))
The Anatomy of an Exploit (NDC TechTown 2019))The Anatomy of an Exploit (NDC TechTown 2019))
The Anatomy of an Exploit (NDC TechTown 2019))Patricia Aas
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesAnkit Rastogi
 

Ähnlich wie Do we need Unsafe in Java? (20)

A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 
What`s new in Java 7
What`s new in Java 7What`s new in Java 7
What`s new in Java 7
 
Java Questions
Java QuestionsJava Questions
Java Questions
 
Nantes Jug - Java 7
Nantes Jug - Java 7Nantes Jug - Java 7
Nantes Jug - Java 7
 
Security Meetup 22 октября. «PHP Unserialize Exploiting». Павел Топорков. Лаб...
Security Meetup 22 октября. «PHP Unserialize Exploiting». Павел Топорков. Лаб...Security Meetup 22 октября. «PHP Unserialize Exploiting». Павел Топорков. Лаб...
Security Meetup 22 октября. «PHP Unserialize Exploiting». Павел Топорков. Лаб...
 
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
 
Vagrant for real
Vagrant for realVagrant for real
Vagrant for real
 
55 new things in Java 7 - Devoxx France
55 new things in Java 7 - Devoxx France55 new things in Java 7 - Devoxx France
55 new things in Java 7 - Devoxx France
 
JNI - Java & C in the same project
JNI - Java & C in the same projectJNI - Java & C in the same project
JNI - Java & C in the same project
 
The mighty js_function
The mighty js_functionThe mighty js_function
The mighty js_function
 
Java 7
Java 7Java 7
Java 7
 
The Anatomy of an Exploit
The Anatomy of an ExploitThe Anatomy of an Exploit
The Anatomy of an Exploit
 
Java
JavaJava
Java
 
Exploitation of counter overflows in the Linux kernel
Exploitation of counter overflows in the Linux kernelExploitation of counter overflows in the Linux kernel
Exploitation of counter overflows in the Linux kernel
 
Mastering Java ByteCode
Mastering Java ByteCodeMastering Java ByteCode
Mastering Java ByteCode
 
No dark magic - Byte code engineering in the real world
No dark magic - Byte code engineering in the real worldNo dark magic - Byte code engineering in the real world
No dark magic - Byte code engineering in the real world
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
 
The Anatomy of an Exploit (NDC TechTown 2019)
The Anatomy of an Exploit (NDC TechTown 2019)The Anatomy of an Exploit (NDC TechTown 2019)
The Anatomy of an Exploit (NDC TechTown 2019)
 
The Anatomy of an Exploit (NDC TechTown 2019))
The Anatomy of an Exploit (NDC TechTown 2019))The Anatomy of an Exploit (NDC TechTown 2019))
The Anatomy of an Exploit (NDC TechTown 2019))
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 

Mehr von Andrei Pangin

The Art of JVM Profiling
The Art of JVM ProfilingThe Art of JVM Profiling
The Art of JVM ProfilingAndrei Pangin
 
Everything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap DumpsEverything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap DumpsAndrei Pangin
 
Down to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap DumpsDown to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap DumpsAndrei Pangin
 
Developing highload servers with Java
Developing highload servers with JavaDeveloping highload servers with Java
Developing highload servers with JavaAndrei Pangin
 
Java tricks for high-load server programming
Java tricks for high-load server programmingJava tricks for high-load server programming
Java tricks for high-load server programmingAndrei Pangin
 
Caching data outside Java Heap and using Shared Memory in Java
Caching data outside Java Heap and using Shared Memory in JavaCaching data outside Java Heap and using Shared Memory in Java
Caching data outside Java Heap and using Shared Memory in JavaAndrei Pangin
 

Mehr von Andrei Pangin (6)

The Art of JVM Profiling
The Art of JVM ProfilingThe Art of JVM Profiling
The Art of JVM Profiling
 
Everything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap DumpsEverything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap Dumps
 
Down to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap DumpsDown to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap Dumps
 
Developing highload servers with Java
Developing highload servers with JavaDeveloping highload servers with Java
Developing highload servers with Java
 
Java tricks for high-load server programming
Java tricks for high-load server programmingJava tricks for high-load server programming
Java tricks for high-load server programming
 
Caching data outside Java Heap and using Shared Memory in Java
Caching data outside Java Heap and using Shared Memory in JavaCaching data outside Java Heap and using Shared Memory in Java
Caching data outside Java Heap and using Shared Memory in Java
 

Kürzlich hochgeladen

Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 

Kürzlich hochgeladen (20)

Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 

Do we need Unsafe in Java?

  • 1. Do we need Unsafe in Java? Andrei Pangin andrey.pangin@corp.mail.ru
  • 3. 3 Can I override object with sun.misc.Unsafe? Is there a way to force unload a class by using the sun.misc.Unsafe class? Can one break a security manager with sun.misc.Unsafe? Rescuing a swallowed Exception in Java How to free memory using Java Unsafe, using a Java reference? Create a mutable java.lang.String Mystic sun.misc.Unsafe
  • 4. 4 Mystic sun.misc.Unsafe How to free memory using Java Unsafe, using a Java reference? Player p = (Player) unsafe.allocateInstance(Player.class); // Is there a way of accessing the memory address // from the object reference unsafe.freeMemory(p.hashCode()); http://stackoverflow.com/questions/24429777
  • 5. 5 Mystic sun.misc.Unsafe Why it is called Unsafe # # A fatal error has been detected by the Java Runtime Environment: # # SIGSEGV (0xb) at pc=0x00002ad221034ee5, pid=3680, tid=1091057984 # # JRE version: Java(TM) SE Runtime Environment (8.0_60-b27) (build 1.8.0_60-b27) # Java VM: Java HotSpot(TM) 64-Bit Server VM (25.60-b23 mixed mode linux-amd64) # Problematic frame: # C [libc.so.6+0x6dee5] cfree+0x25 # # An error report file with more information is saved as: # /home/apangin/hs_err_pid3680.log #
  • 6. 6 What is Unsafe actually • Bridge between Class Library and JVM • For use inside JDK - NIO - AWT - Reflection - java.util.concurrent - MethodHandles • Exists in many JVMs, even on Android Mystic sun.misc.Unsafe
  • 7. 7 Mystic sun.misc.Unsafe public final class Unsafe { static { registerNatives(); sun.reflect.Reflection.registerMethodsToFilter(Unsafe.class, "getUnsafe"); } private Unsafe() {} private static final Unsafe theUnsafe = new Unsafe(); @CallerSensitive public static Unsafe getUnsafe() { Class cc = Reflection.getCallerClass(); if (cc.getClassLoader() != null) throw new SecurityException("Unsafe"); return theUnsafe; }
  • 8. 8 Mystic sun.misc.Unsafe Getting Unsafe public static Unsafe getUnsafe() throws Exception { Field f = Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); return (Unsafe) f.get(null); }
  • 9. 9 Security hole? Security Manager is off by default $ java -Djava.security.manager java.security.AccessControlException: access denied ("java.lang.RuntimePermission" "accessClassInPackage.sun.misc") Mystic sun.misc.Unsafe
  • 10. 10 Mystic sun.misc.Unsafe You’ve been warned! $ javac Test.java Test.java:2: warning: Unsafe is internal proprietary API and may be removed in a future release import sun.misc.Unsafe; ^ $ javac -XDignore.symbol.file Test.java
  • 12. 12 Inside Unsafe public native long allocateMemory(long bytes); public native long reallocateMemory(long address, long bytes); public native void freeMemory(long address); public native byte getByte(long address); public native void putByte(long address, byte x); public native int getInt(Object o, long offset); public native void putInt(Object o, long offset, int x); public native long objectFieldOffset(Field f); public native long staticFieldOffset(Field f); public native int arrayBaseOffset(Class<?> arrayClass); public native void copyMemory(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
  • 13. 13 package snow.misc; public class MyUnsafe { public native int getInt(long address); #include <jni.h> JNIEXPORT jint JNICALL Java_snow_misc_MyUnsafe(JNIEnv* env, jobject myUnsafe, jlong address) { return *(jint*)address; } Inside Unsafe
  • 14. 14 Inside Unsafe JNI call 1. Create stack frame 2. Move arguments according to ABI 3. Wrap objects into JNI handles 4. Obtain JNIEnv* and jclass 5. Trace method_entry 6. Lock if synchronized 7. Lazy lookup and linking 8. in_java  in_native thread transition 9. Call the native function 10. Check for safepoint 11. Switch state to in_java 12. Unlock if synchronized 13. Notify method_exit 14. Unwrap result, reset JNI handles block 15. Handle exceptions 16. Remove stack frame
  • 15. 15 Implementation • Most methods are JVM intrinsics - E.g. getInt is a single MOV instruction • Executed in Java or VM context - Beware of mapped I/O (safepoint pauses) Inside Unsafe
  • 16. 16 public native int getIntVolatile(Object o, long offset); public native void putIntVolatile(Object o, long offset, int x); public native void putOrderedInt(Object o, long offset, int x); public final native boolean compareAndSwapInt(Object o, long offset, int expected, int x); /* @since 1.8 */ public native void loadFence(); public native void storeFence(); public native void fullFence(); public final int getAndAddInt(Object o, long offset, int delta) { int v; do { v = getIntVolatile(o, offset); } while (!compareAndSwapInt(o, offset, v, v + delta)); return v; } Inside Unsafe
  • 17. 17 i.getAndAdd(5) lock addl $0x5,0xc(%r10)loop: mov 0xc(%r10),%eax mov %eax,%r11d add $0x5,%r11d lock cmpxchg %r11d,0xc(%r10) sete %r11b movzbl %r11b,%r11d test %r11d,%r11d je loop JDK 7u72 -XX:+PrintAssembly JDK 8u60 83 46 15 11 132 105 45 43 1 2 3 4 ops/μs threads Inside Unsafe
  • 18. 18 Inside Unsafe public native Class<?> defineClass(String name, byte[] b, int off, int len, ClassLoader loader, ProtectionDomain protectionDomain); public native Class<?> defineAnonymousClass(Class<?> hostClass, byte[] data, Object[] cpPatches); public native Object allocateInstance(Class<?> cls) throws InstantiationException; public native void park(boolean isAbsolute, long time); public native void unpark(Object thread); public native int getLoadAverage(double[] loadavg, int nelems); public native void throwException(Throwable ee);
  • 19. 19 Inside Unsafe Deprecated in JDK 8, removed in 9 @Deprecated public native void monitorEnter(Object o); @Deprecated public native void monitorExit(Object o); @Deprecated public native boolean tryMonitorEnter(Object o); // Phantom HotSpot intrinsics public native void prefetchRead(Object o, long offset); public native void prefetchWrite(Object o, long offset);
  • 21. 21 Off-heap collections • Lists, sets, maps - Large capacity > 2 GB - Predictable GC pauses - No heap fragmentation (CMS Promotion Failures) - Data locality Use cases
  • 22. 22 Data locality Key Value Key Value Map.Entry Off-heap layout a b c a b c a b c Use cases
  • 23. 23 Use cases Off-heap hash map 0 addr 0 … addr 0 hash time next key (?) value hash time 0 key (?) value entry one.nio.mem.SharedMemoryMap
  • 24. 24 OffheapLongList public OffheapLongList(int initialCapacity) { capacity = Math.max(initialCapacity, 4); base = unsafe.allocateMemory(capacity * 8L); } public void add(long value) { if (size >= capacity) { capacity *= 2; base = unsafe.reallocateMemory(base, capacity * 8L); } unsafe.putLong(base + size * 8L, value); size++; } public long get(int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(); } return unsafe.getLong(base + index * 8L); }
  • 25. 25 Use cases When to free memory? class OffheapCleaner<T> extends PhantomReference<T> { static final ReferenceQueue<T> queue = new ReferenceQueue<T>(); final long address; OffheapCleaner(T referent, long address) { super(referent, queue); this.address = address; } } while (true) { OffheapCleaner<T> cleaner = (OffheapCleaner<T>) queue.remove(); unsafe.freeMemory(cleaner.address); }
  • 26. 26 Why not ByteBuffers? • Size limit (Integer.MAX_VALUE) • Not thread-safe • No freeMemory public void forceClean(ByteBuffer buffer) { ((sun.nio.ch.DirectBuffer) buffer)).cleaner().clean(); } Use cases
  • 27. 27 sun.nio.ch.FileChannelImpl try { // If no exception was thrown from map0, the address is valid addr = map0(imode, mapPosition, mapSize); } catch (OutOfMemoryError x) { // An OutOfMemoryError may indicate that we've exhausted memory // so force gc and re-attempt map System.gc(); try { Thread.sleep(100); } catch (InterruptedException y) { Thread.currentThread().interrupt(); } try { addr = map0(imode, mapPosition, mapSize); } catch (OutOfMemoryError y) { // After a second OOME, fail throw new IOException("Map failed", y); } }
  • 28. 28 Cassandra // Hoping GC will remove some not used tables. System.gc(); Thread.sleep(60000); location = estimateFlushPath(); if (location!=null) return new File(location, ssTableFileName).getAbsolutePath(); // Hoping GC will remove some not used tables - sometimes 2 GC cycles are needed. logger_.warn("Still Insufficient disk space to flush "+ssTableFileName); System.gc(); Thread.sleep(60000); location = estimateFlushPath();
  • 29. 29 Use cases Direct buffers ↔ Unsafe Field addressField = Buffer.class.getDeclaredField("address"); addressField.setAccessible(true); // ByteBuffer  address long address = addressField.getLong(byteBuffer); // address  ByteBuffer ByteBuffer result = prototype.duplicate(); addressField.setLong(result, address);
  • 30. 30 Use cases Benchmark Benchmark Mode Cnt Score Error Units b.byteBuffer thrpt 15 290,832 ± 7,858 ops/us b.rawMemory thrpt 15 480,799 ± 2,610 ops/us public void byteBuffer() { buf.putLong(0, order.timestamp); buf.put(8, order.operationType); buf.putInt(9, order.productId); buf.putFloat(13, order.price); } public void rawMemory() { unsafe.putLong(addr + 0, order.timestamp); unsafe.put(addr + 8, order.operationType); unsafe.putInt(addr + 9, order.productId); unsafe.putFloat(addr + 13, order.price); }
  • 31. 31 I/O and persistence • Persistent caches and storages - Memory-mapped files (64-bit) - Shared memory • Cooperation with OS - Pointer arithmetic, alignment - mlock, madvise etc. Use cases
  • 32. 32 Use cases Mapping large files // Mapping Method map0 = FileChannelImpl.class.getDeclaredMethod( "map0", int.class, long.class, long.class); map0.setAccessible(true); long addr = (Long) map0.invoke(f.getChannel(), 1, 0L, f.length()); // Unmapping Method unmap0 = FileChannelImpl.class.getDeclaredMethod( "unmap0", long.class, long.class); unmap0.setAccessible(true); unmap0.invoke(null, addr, length);
  • 33. 33 IPC, Messaging • Concurrent off-heap buffers and queues • High-performance messaging - Disruptor - Aeron: 6M msg/s • Shared data structures - Chronicle Map Use cases
  • 34. 34 Use cases Coding / Decoding do { v1 += getInt(buf, offset) * P2; v1 = ((v1 << 13) | (v1 >>> 19)) * P1; v2 += getInt(buf, offset + 4) * P2; v2 = ((v2 << 13) | (v2 >>> 19)) * P1; v3 += getInt(buf, offset + 8) * P2; v3 = ((v3 << 13) | (v3 >>> 19)) * P1; v4 += getInt(buf, offset + 12) * P2; v4 = ((v4 << 13) | (v4 >>> 19)) * P1; } while ((offset += 16) <= limit); public int getInt(byte[] buf, int off) { return (buf[off] & 0xff) | (buf[off + 1] & 0xff) << 8 | (buf[off + 2] & 0xff) << 16 | (buf[off + 3]) << 24; } public int getInt(byte[] buf, int off) { return unsafe.getInt(buf, byteArrayOffset + off); } xxHash loop
  • 35. 35 Use cases Benchmark Benchmark (length) Mode Cnt Score Error Units b.xxhashArray 10 thrpt 5 61697,875 ± 849,565 ops/ms b.xxhashArray 100 thrpt 5 13552,417 ± 91,039 ops/ms b.xxhashArray 1000 thrpt 5 1749,843 ± 12,290 ops/ms b.xxhashUnsafe 10 thrpt 5 77358,056 ± 675,536 ops/ms b.xxhashUnsafe 100 thrpt 5 34153,796 ± 319,798 ops/ms b.xxhashUnsafe 1000 thrpt 5 5259,813 ± 43,870 ops/ms
  • 36. 36 Serialization • Fast conversion to/from byte[] • Access private fields - Reflection vs. Unsafe • Instantiate objects without constructor - unsafe.allocateInstance() Use cases
  • 37. 37 one-nio serialization • Extend sun.reflect.MagicAccessorImpl - no bytecode verification • Fast and compact • Supports class evolution - Java serialization - JBoss - Kryo - Protobuf Use cases
  • 38. 38 Native APIs • Own network library - Linux-specific TCP features and socket options - Integration with OpenSSL • I/O and memory management - mlock - posix_fadvise • setuid • sched_setaffinity Use cases
  • 40. 40 Removal of sun.misc.Unsafe An absolute disaster Cassandra Netty Guava Hazelcast Mockito GWT Hadoop Zookeeper Kafka Gson Neo4j Grails Spring Disruptor JRuby Scala Akka
  • 41. 41 Why? Removal of sun.misc.Unsafe Integrity and security Maintenance costs
  • 42. 42 Chronology • JEP 200: The Modular JDK • Mark Reinhold speaks at Devoxx • Chris Engelbert started a discussion group • Apocalyptic post at blog.dripstat.com • JCrete • JVM Language Summit • JEP 260: Encapsulate Most Internal APIs Removal of sun.misc.Unsafe 2014 / 07 2015 / 06 2015 / 07 2015 / 08
  • 43. 43 Migration plan • Replacement in JDK 8  hide in JDK 9 - sun.misc.BASE64Encoder etc. - Available via command-line flag • No replacement in JDK 8  available outside - sun.misc.Unsafe, sun.reflect.ReflectionFactory - sun.misc.Cleaner, sun.misc.SignalHandler • Replacement in JDK 9  hide in JDK 9, remove in JDK 10 Removal of sun.misc.Unsafe
  • 45. 45 Project Panama • JEP 191: Foreign Function Interface • Expected in Java 10 • JNR Replacements public interface LibC { int setuid(@uid_t long uid); } LibC libc = LibraryLoader.create(LibC.class).load("c"); libc.setuid(restrictedUser);
  • 46. 46 JEP 193: VarHandles • Targeted for Java 9 Replacements class Queue { int size; ... } VarHandle queueSize = MethodHandles.lookup(). findVarHandle(Queue.class, "size", int.class); queueSize.addAndGet(10);
  • 47. 47 Replacements // Desired syntax VarHandle queueSize = Queue::size; VarHandle intElementHandle = MethodHandles.lookup() .arrayElementVarHandle(int[].class); VarHandle longArrayViewHandle = MethodHandles.lookup() .arrayElementViewHandle(byte[].class, long[].class, true, false); ByteBuffer byteBuffer = ByteBuffer.allocateDirect(8); VarHandle bufferView = MethodHandles.lookup() .byteBufferViewVarHandle(long[].class, true, false);
  • 48. 48 Replacements public static void fullFence(); public static void acquireFence() public static void releaseFence(); public static void loadLoadFence(); public static void storeStoreFence(); • getRelaxed, getVolatile, getOpaque • setRelaxed, setVolatile, setOpaque • getAquire, setRelease • compareAndSet, compareAndExchangeVolatile • compareAndExchangeAcquire, compareAndExchangeRelease • weakCompareAndSet, weakCompareAndSetAcquire, weakCompareAndSetRelease • getAndSet, getAndAdd, addAndGet
  • 49. 49 Replacements // Not in Java 9 MemoryRegion region = MemoryRegion.allocateNative( "myname", MemoryRegion.UNALIGNED, Long.MAX_VALUE); VarHandle regionView = region.asVarHandle(long[].class, true, false); regionView.set(region, 0, Long.MAX_VALUE); return regionView.get(region, 0);
  • 50. 50 Replacements Serialization ReflectionFactory reflectionFactory = ReflectionFactory.getReflectionFactory(); Constructor<?> baseConstructor = Object.class.getDeclaredConstructor(); Constructor<?> constructor = reflectionFactory. newConstructorForSerialization(Foo.class, baseConstructor); return (Foo) constructor.newInstance(); jobject AllocObject(JNIEnv *env, jclass clazz); JNI
  • 51. 51 Replacements Можно жить и без Unsafe но грустно
  • 53. 53 Unsafe bugs JVM Bugs # # A fatal error has been detected by the Java Runtime Environment: # # SIGSEGV (0xb) at pc=0x00002b9fd9f44898, pid=19692, tid=1096575296 # # JRE version: 6.0_24-b07 # Java VM: Java HotSpot(TM) 64-Bit Server VM (19.1-b02 mixed mode linux-amd64) # Problematic frame: # J Test.loop(Lsun/misc/Unsafe;J)V # # An error report file with more information is saved as: # /home/apangin/hs_err_pid19692.log # # If you would like to submit a bug report, please visit: # http://java.sun.com/webapps/bugreport/crash.jsp # for (int i = 0; i < BUF_SIZE; i += 8) unsafe.putLong(addr + i, Long.reverseBytes(i));
  • 54. 54 JVM Bugs • JDK-6968348: Unsafe + Long.reverseBytes • JDK-7196566: Reported by me  • JDK-8022783: Non-public bug in C2 • JDK-8087134: Wrong C1 optimization Unsafe bugs 6u25 7u40 7u71 8u60 -XX:-TieredCompilation
  • 55. 55 Unsafe bugs Not yet fixed RandomAccessFile raf = new RandomAccessFile("/dev/shm/cache.tmp", "rw"); raf.setLength(5_000_000_000L); MappedByteBuffer buf = raf.getChannel().map(READ_WRITE, 0, raf.length()); for (int i = 0; i < 5000; i++) { buf.put(new byte[1_000_000]); } SIGBUS
  • 57. 57 Development @ OK • Blog - http://habrahabr.ru/company/odnoklassniki • Open source - https://github.com/odnoklassniki • Career - http://v.ok.ru Thank you