SlideShare une entreprise Scribd logo
1  sur  113
Télécharger pour lire hors ligne
http://www.superbwallpapers.com/fantasy/post-apocalyptic-tower-bridge-london-26546/
A Post-Apocalyptic
sun.misc.Unsafe
World
www.hazelcast.com@noctarius2k
Who’s that dude?
• Chris Engelbert
• Manager Developer Relations @Hazelcast
• Twitter-Senpai
• Java-Passionist (10+ years)
• Performance
• Garbage Collection
• Benchmark Fairytales
Disclaimer
This talk is not going to be negative!
Disclaimer
But certain things are highly speculative

and APIs or ideas might change by
tomorrow!
http://www.underwhelmedcomic.com/wp-content/uploads/2012/03/runningdude.jpg
sun.misc.Scissors
sun.misc.Unsafe - What you (don’t) know
sun.misc.Unsafe - What you (don’t) know
• Internal class (sun.misc Package)
sun.misc.Unsafe - What you (don’t) know
• Internal class (sun.misc Package)
sun.misc.Unsafe - What you (don’t) know
• Internal class (sun.misc Package)
• Used inside the JVM / JRE
sun.misc.Unsafe - What you (don’t) know
• Internal class (sun.misc Package)
• Used inside the JVM / JRE
// Unsafe mechanics

private static final sun.misc.Unsafe U;

private static final long QBASE;

private static final long QLOCK;

private static final int ABASE;

private static final int ASHIFT;

static {

try {

U = sun.misc.Unsafe.getUnsafe();

Class<?> k = WorkQueue.class;

Class<?> ak = ForkJoinTask[].class;

QBASE = U.objectFieldOffset

(k.getDeclaredField("base"));

QLOCK = U.objectFieldOffset

(k.getDeclaredField("qlock"));

ABASE = U.arrayBaseOffset(ak);

int scale = U.arrayIndexScale(ak);

if ((scale & (scale - 1)) != 0)

throw new Error("data type scale not a power of two");

ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);

} catch (Exception e) {

throw new Error(e);

}

}

}
example:
java.util.concurrent.ForkJoinPool
sun.misc.Unsafe - What you (don’t) know
• Internal class (sun.misc Package)
• Used inside the JVM / JRE
• Used outside as well
sun.misc.Unsafe - What you (don’t) know
• Internal class (sun.misc Package)
• Used inside the JVM / JRE
• Used outside as well (good
// Deserialization
public Object readObject(InputStream is) {

SomeType element = unsafe.allocateInstance(SomeType.class);

element.deserializeValues(is);

return element;

}
sun.misc.Unsafe - What you (don’t) know
• Internal class (sun.misc Package)
• Used inside the JVM / JRE
• Used outside as well (good, bad)
#
# A fatal error has been detected by the Java Runtime Environment:
#
# SIGSEGV (0xb) at pc=0x00000001067314b5, pid=25244, tid=5891
#
# JRE version: Java(TM) SE Runtime Environment (8.0_05-b13) (build 1.8.0_05-b13)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.5-b02 mixed mode bsd-amd64 compressed oops)
# Problematic frame:
# V [libjvm.dylib+0x5314b5] Unsafe_SetNativeAddress+0x36
#
# An error report file with more information is saved as:
# /Users/noctarius/git/hazelcast-only.idea/hs_err_pid25244.log
#
# If you would like to submit a bug report, please visit:
# http://bugreport.sun.com/bugreport/crash.jsp
#
sun.misc.Unsafe - What you (don’t) know
• Internal class (sun.misc Package)
• Used inside the JVM / JRE
• Used outside as well (good / bad)
• Never intended for outside use
sun.misc.Unsafe - What you (don’t) know
• Internal class (sun.misc Package)
• Used inside the JVM / JRE
• Used outside as well (good / bad)
• Never intended for outside use
sun.misc.Unsafe - What you (don’t) know
• Internal class (sun.misc Package)
• Used inside the JVM / JRE
• Used outside as well (good / bad)
• Never intended for outside use
• Used by popular:
• Applications
• Frameworks
• Libraries
MapDB
Netty
Hazelcast
Cassandra
Mockito
EasyMock
JMock
Scala
Spock
Robolectric
Grails
Gson
Neo4j
Apache Ignite
Apache Spark
Apache Kafka
Apache Wink
Apache Storm
Apache Flink
Apache Continuum
Zookeeper
Dropwizard
Metrics (AOP)
Kryo
Byte Buddy
Hibernate
Liquibase
Spring Framework
Ehcache
OrientDB
Chronicle
Apache Hadoop
Apache HBase
GWT
Disruptor
JRuby
AkkaAgrona
Aeron
Simple Binary Encoding
XRebel
Presto
jol
ActivePivot
LWJGL
XAP
XStream
CapLogic
WildFly
Infinispan
MapDB
Netty
Hazelcast
Cassandra
Mockito
EasyMock
JMock
Scala
Spock
Robolectric
Grails
Gson
Neo4j
Apache Ignite
Apache Spark
Apache Kafka
Apache Wink
Apache Storm
Apache Flink
Apache Continuum
Zookeeper
Dropwizard
Metrics (AOP)
Kryo
Byte Buddy
Hibernate
Liquibase
Spring Framework
Ehcache
OrientDB
Chronicle
Apache Hadoop
Apache HBase
GWT
Disruptor
JRuby
AkkaAgrona
Aeron
Simple Binary Encoding
XRebel
Presto
jol
ActivePivot
LWJGL
XAP
XStream
CapLogic
WildFly
Infinispan
sun.misc.Unsafe
is only supported on HotSpot JVMs anyways, isn’t it?
sun.misc.Unsafe
is only supported on HotSpot JVMs anyways, isn’t it?
No!
Language URL sun.misc.Unsafe
Avian C++ https://github.com/ReadyTalk/avian Yes
BicaVM JavaScript https://github.com/nurv/BicaVM No
Cacao C http://www.cacaojvm.org Yes
Excelsior JVM C / C++ ? http://www.excelsiorjet.com Yes
Dalvik / ART / Android C / C++ https://source.android.com/source/index.html Yes
Graal mainly Java http://openjdk.java.net/projects/graal Yes
GCJ C / C++ https://gcc.gnu.org/java Yes
HaikuVM C http://haiku-vm.sourceforge.net No
IBM J9 C / C++ ? http://www.ibm.com/developerworks/java/jdk/index.html Yes
IcedTea C / C++ http://icedtea.classpath.org/wiki/Main_Page Yes
IKVM.NET C# http://www.ikvm.net Yes
Jamiga C https://sourceforge.net/projects/jamiga2 No
JamVM C http://jamvm.sourceforge.net Yes
JatoVM C http://jatovm.org Yes
JikesRVM C microkernel, Java http://www.jikesrvm.org Yes
JNode C microkernel, Java http://www.jnode.org Yes
JVM.go Go https://github.com/zxh0/jvm.go Yes
JX C http://www4.cs.fau.de/Projects/JX/index.html No
Kaffe C https://github.com/kaffe/kaffe Yes
NanoVM C http://harbaum.org/till/nanovm/index.shtml No
OpenJDK / Oracle / Zulu C / C++ http://openjdk.java.net Yes
RoboVM C / C++ / ObjC https://robovm.com Yes
SAPJVM C / C++ ? http://help.sap.com/saphelp_nwce10/helpdata/en/47/
dc90b4ef17452289f9128b8c2bbd77/content.htm
Yes
Waratek Multitenant JVM C / C++ ? http://www.waratek.com Yes
Zing JVM C / C++ ? https://www.azul.com/products/zing Yes
Use Cases - The Good Ones!
Use Cases - The Good Ones!
• Low Latency, GC Overhead
Use Cases - The Good Ones!
• Low Latency, GC Overhead
Caution: Overly simplified!
Unsafe unsafe = findUnsafe();

long baseAddress = unsafe.allocateMemory(8);


class Point {

long offsetX = 0;

long offsetY = 4;



int getX(long baseAddress) {
return unsafe.getInt(baseAddress + offsetX);
}


int getY(long baseAddress) {
return unsafe.getInt(baseAddress + offsetY);
}

}
Use Cases - The Good Ones!
• Low Latency, GC Overhead
• Fast (de-)serialization
Use Cases - The Good Ones!
• Low Latency, GC Overhead
• Fast (de-)serialization
// Deserialization
public Object readObject(InputStream is) {

SomeType element = unsafe.allocateInstance(SomeType.class);

element.deserializeValues(is);

return element;

}
Use Cases - The Good Ones!
• Low Latency, GC Overhead
• Fast (de-)serialization
• 64bit Memory regions
Use Cases - The Good Ones!
• Low Latency, GC Overhead
• Fast (de-)serialization
• 64bit Memory regions
long baseAddress = unsafe.allocateMemory(Long.MAX_VALUE);

unsafe.putInt(baseAddress + Long.MAX_VALUE - 4, Integer.MAX_VALUE);
Use Cases - The Good Ones!
• Low Latency, GC Overhead
• Fast (de-)serialization
• 64bit Memory regions
• Atomic memory operations
Use Cases - The Good Ones!
• Low Latency, GC Overhead
• Fast (de-)serialization
• 64bit Memory regions
• Atomic memory operations
unsafe.compareAndSwapInt(this, offsetField, oldValue, newValue);

unsafe.compareAndSwapLong(this, offsetField, oldValue, newValue);

unsafe.compareAndSwapObject(this, offsetField, oldObject, newObject);
Use Cases - The Good Ones!
• Low Latency, GC Overhead
• Fast (de-)serialization
• 64bit Memory regions
• Atomic memory operations
• Efficient memory layout
Use Cases - The Good Ones!
• Low Latency, GC Overhead
• Fast (de-)serialization
• 64bit Memory regions
• Atomic memory operations
• Efficient memory layout
class Point {

long offsetX = 0;

long offsetY = 4;

}
offsetX
offsetY
Use Cases - The Good Ones!
• Low Latency, GC Overhead
• Fast (de-)serialization
• 64bit Memory regions
• Atomic memory operations
• Efficient memory layout
• Fast field / memory access
Use Cases - The Good Ones!
• Low Latency, GC Overhead
• Fast (de-)serialization
• 64bit Memory regions
• Atomic memory operations
• Efficient memory layout
• Fast field / memory access
long versionFieldOffset = unsafe.objectFieldOffset(versionField);



long version = unsafe.getLong(this, versionFieldOffset);



unsafe.putLong(this, versionFieldOffset, 10L);
Use Cases - The Good Ones!
• Low Latency, GC Overhead
• Fast (de-)serialization
• 64bit Memory regions
• Atomic memory operations
• Efficient memory layout
• Fast field / memory access
• Access to array elements with volatile semantics
Use Cases - The Good Ones!
• Low Latency, GC Overhead
• Fast (de-)serialization
• 64bit Memory regions
• Atomic memory operations
• Efficient memory layout
• Fast field / memory access
• Access to array elements with volatile semantics
long base = unsafe.arrayBaseOffset(int[].class);

long index = unsafe.arrayIndexScale(int[].class);



unsafe.getIntVolatile(array, base + (index * 3));
Use Cases - The Good Ones!
• Low Latency, GC Overhead
• Fast (de-)serialization
• 64bit Memory regions
• Atomic memory operations
• Efficient memory layout
• Fast field / memory access
• Access to array elements with volatile semantics
• Custom memory fences
Use Cases - The Good Ones!
• Low Latency, GC Overhead
• Fast (de-)serialization
• 64bit Memory regions
• Atomic memory operations
• Efficient memory layout
• Fast field / memory access
• Access to array elements with volatile semantics
• Custom memory fences
unsafe.fullFence();


unsafe.storeFence();


unsafe.loadFence();
Use Cases - The Good Ones!
• Low Latency, GC Overhead
• Fast (de-)serialization
• 64bit Memory regions
• Atomic memory operations
• Efficient memory layout
• Fast field / memory access
• Access to array elements with volatile semantics
• Custom memory fences
• Fast interaction with native code
Use Cases - The Good Ones!
• Low Latency, GC Overhead
• Fast (de-)serialization
• 64bit Memory regions
• Atomic memory operations
• Efficient memory layout
• Fast field / memory access
• Access to array elements with volatile semantics
• Custom memory fences
• Fast interaction with native code
long addr = unsafe.allocateMemory(50);

copyBytes(addr, byteArray);

nativeCall(addr);
Get Access
Get Access
Easy One (not working outside the JRE / JDK)
Unsafe unsafe = Unsafe.getUnsafe();
Get Access
The Ugly One
private static final Unsafe UNSAFE;

static {

try {

Field theUnsafeField = Unsafe.class.getDeclaredField("theUnsafe");

theUnsafeField.setAccessible(true);

UNSAFE = (Unsafe) theUnsafeField.get(Unsafe.class);



} catch (Exception e) {

// We need you! =(

throw new Error(e);

}

}
Get Access
The Working One
(at least for more than just HotSpot)
private static Unsafe findUnsafe() {

try {

return Unsafe.getUnsafe();

} catch (SecurityException se) {

return AccessController.doPrivileged(new PrivilegedAction<Unsafe>() {

@Override

public Unsafe run() {

try {

Class<Unsafe> type = Unsafe.class;

try {

Field field = type.getDeclaredField("theUnsafe");

field.setAccessible(true);

return type.cast(field.get(type));



} catch (Exception e) {

for (Field field : type.getDeclaredFields()) {

if (type.isAssignableFrom(field.getType())) {

field.setAccessible(true);

return type.cast(field.get(type));

}

}

}

} catch (Exception e) {

throw new RuntimeException("Unsafe unavailable", e);

}

throw new RuntimeException("Unsafe unavailable");

}

});

}

}
Get Access
The Tricky One
private static final Unsafe UNSAFE;

static {

try {

Constructor<Unsafe> constructor =
Unsafe.class.getDeclaredConstructor();


constructor.setAccessible(true);

UNSAFE = constructor.newInstance();



} catch (Exception e) {

// We need you! =(

throw new Error(e);

}

}
Get Access
Does Any Of This Feel Right?
Weird!
No!
WAAAAAT!?!?
No!
Let me be blunt -- sun.misc.Unsafe must die in a fire. It is -- wait
for it -- Unsafe. It must go. Ignore any kind of theoretical rope and
start the path to righteousness _*/now/*_. It is still years until the
end of public updates to JDK 8, so we have /*years */to work this out
properly. But sticking our heads in the collective sands and hoping for
trivial work arounds to Unsafe is not going to work. If you're using
Unsafe, this is the year to explain where the API is broken and get it
straight....
Please help us kill Unsafe, kill Unsafe dead, kill Unsafe right, and do
so as quickly as possible to the ultimate benefit of everyone.
Wed Apr 8 19:15:42 UTC 2015, OpenJFX Mailinglist, Donald Smith, Oracle
http://mail.openjdk.java.net/pipermail/openjfx-dev/2015-April/017028.html
Let me be blunt -- sun.misc.Unsafe must die in a fire. It is -- wait
for it -- Unsafe. It must go. Ignore any kind of theoretical rope and
start the path to righteousness _*/now/*_. It is still years until the
end of public updates to JDK 8, so we have /*years */to work this out
properly. But sticking our heads in the collective sands and hoping for
trivial work arounds to Unsafe is not going to work. If you're using
Unsafe, this is the year to explain where the API is broken and get it
straight....
Please help us kill Unsafe, kill Unsafe dead, kill Unsafe right, and do
so as quickly as possible to the ultimate benefit of everyone.
Wed Apr 8 19:15:42 UTC 2015, OpenJFX Mailinglist, Donald Smith, Oracle
http://mail.openjdk.java.net/pipermail/openjfx-dev/2015-April/017028.html
Let me be blunt -- sun.misc.Unsafe must die in a fire. It is -- wait
for it -- Unsafe. It must go. Ignore any kind of theoretical rope and
start the path to righteousness _*/now/*_. It is still years until the
end of public updates to JDK 8, so we have /*years */to work this out
properly. But sticking our heads in the collective sands and hoping for
trivial work arounds to Unsafe is not going to work. If you're using
Unsafe, this is the year to explain where the API is broken and get it
straight....
Please help us kill Unsafe, kill Unsafe dead, kill Unsafe right, and do
so as quickly as possible to the ultimate benefit of everyone.
Wed Apr 8 19:15:42 UTC 2015, OpenJFX Mailinglist, Donald Smith, Oracle
http://mail.openjdk.java.net/pipermail/openjfx-dev/2015-April/017028.html
Let me be blunt -- sun.misc.Unsafe must die in a fire. It is -- wait
for it -- Unsafe. It must go. Ignore any kind of theoretical rope and
start the path to righteousness _*/now/*_. It is still years until the
end of public updates to JDK 8, so we have /*years */to work this out
properly. But sticking our heads in the collective sands and hoping for
trivial work arounds to Unsafe is not going to work. If you're using
Unsafe, this is the year to explain where the API is broken and get it
straight....
Please help us kill Unsafe, kill Unsafe dead, kill Unsafe right, and do
so as quickly as possible to the ultimate benefit of everyone.
Wed Apr 8 19:15:42 UTC 2015, OpenJFX Mailinglist, Donald Smith, Oracle
http://mail.openjdk.java.net/pipermail/openjfx-dev/2015-April/017028.html
Oracle created a new Taskforce
Oracle created a new Taskforce
K.U.T.T. - Kill Unsafe To Total death
Let me be blunt -- sun.misc.Unsafe must die in a fire. It is -- wait
for it -- Unsafe. It must go. Ignore any kind of theoretical rope and
start the path to righteousness _*/now/*_. It is still years until the
end of public updates to JDK 8, so we have /*years */to work this out
properly. But sticking our heads in the collective sands and hoping for
trivial work arounds to Unsafe is not going to work. If you're using
Unsafe, this is the year to explain where the API is broken and get it
straight....
Please help us kill Unsafe, kill Unsafe dead, kill Unsafe right, and do
so as quickly as possible to the ultimate benefit of everyone.
Wed Apr 8 19:15:42 UTC 2015, OpenJFX Mailinglist, Donald Smith, Oracle
http://mail.openjdk.java.net/pipermail/openjfx-dev/2015-April/017028.html
So What’s Coming?
private static final Unsafe UNSAFE = findUnsafe();
private static long VERSION_OFFSET = findVersionOffset();
// Updated through Unsafe only!
private volatile long version = 0;
public long increment() {
while(true) {
long version = this.version;
long newVersion = version + 1;
if (UNSAFE.compareAndSwapLong(
this, VERSION_OFFSET, version, newVersion)) {
return newVersion;
}
}
}
Atomic Updates
Atomic Updates
private final AtomicLong version = new AtomicLong(0);
public long increment() {
return version.incrementAndGet();
}
Atomic Updates
private static final AtomicLongFieldUpdater<Record> VERSION =

AtomicLongFieldUpdater.newUpdater(Record, "version");

// Updated through atomic field updater only!

private volatile long version = 0;



public long increment() {

return VERSION.incrementAndGet(this);

}
Atomic Updates
private static final VarHandle VERSION = findVersionVarHandle();



// Updated through VarHandle only!

private volatile long version = 0;



public long increment() {

return (long) VERSION.addAndGet(this, 1);

}
Atomic Updates
public static VarHandle findVersionVarHandle() {

try {

return MethodHandles.lookup().

findFieldVarHandle(Record.class, "version", long.class);



} catch (Exception e) {

throw new Error(e);

}

}
Memory Management
public long memory() {

long address = UNSAFE.allocateMemory(8);


UNSAFE.putLong(address, Long.MAX_VALUE);


return UNSAFE.getLong(address);

}
Memory Management
public long memory() {

ByteBuffer byteBuffer = ByteBuffer.allocateDirect(8);



byteBuffer.putLong(0, Long.MAX_VALUE);



return byteBuffer.getLong(0);

}
Memory Management
public long memory() {

ByteBuffer byteBuffer = ByteBuffer.allocateDirect(8);



VarHandle bufferView =

MethodHandles.byteBufferViewVarHandle(long[].class, true);



bufferView.set(byteBuffer, 0, Long.MAX_VALUE);



return bufferView.get(byteBuffer, 0);

}
Memory Management
public long memory() {

MemoryRegion region = MemoryRegion.allocateNative

("myname", MemoryRegion.UNALIGNED, Long.MAX_VALUE);



VarHandle regionView = MethodHandles.

memoryRegionViewVarHandle(long[].class, true);


regionView.set(region, 0, Long.MAX_VALUE);


return regionView.get(region, 0);

}
Memory Management
public long memory() {

MemoryRegion region = MemoryRegion.allocateNative

("myname", MemoryRegion.UNALIGNED, Long.MAX_VALUE);



VarHandle regionView = MethodHandles.

memoryRegionViewVarHandle(long[].class, true);


regionView.set(region, 0, Long.MAX_VALUE);


return regionView.get(region, 0);

}
Memory Management
public long memory(long index) {

try (Scope scope = new NativeScope()) {

Pointer<Long> ptr = scope.allocate(

NativeLibrary.createLayout(long.class), numElements);



Reference<Long> ref = ptr.offset(index).deref();



ref.set(Long.MAX_VALUE);



return ref.get();

}

}
Memory Management
Deserialization
private static final Unsafe UNSAFE = findUnsafe();



private static final long VALUE_OFFSET = findValueOffset();



public String deserializeString() throws Exception {

char[] chars = readCharsFromStream();

String allocated = (String) UNSAFE.allocateInstance(String.class);

UNSAFE.putObjectVolatile(allocated, VALUE_OFFSET, chars);

return allocated;

}
Deserialization
public String deserializeString() throws Exception {

char[] chars = readCharsFromStream().freeze();



ReflectionFactory reflectionFactory =

ReflectionFactory.getReflectionFactory();



Constructor<String> constructor = reflectionFactory

.newConstructorForSerialization(String.class, char[].class);



return constructor.newInstance(chars);

}
Interoperability
extern c {

JNIEXPORT int JNICALL

Java_ProcessIdentifier_getProcessId(JNIEnv *, jobject);

}



JNIEXPORT int JNICALL

Java_ProcessIdentifier_getProcessId(JNIEnv *env, jobject thisObj) {

return getpid();

}



public class ProcessIdentifier {

static {

System.loadLibrary("processidentifier");

}



public native void talk();

}
Interoperability
interface LibC {

void getpid();

}



public int call() {

LibC c = LibraryLoader.create(LibC.class).load("c");

return c.getpid();

}
Interoperability
public void call() {
MethodType intType = MethodType.methodType(int.class);


MethodHandle handle = MethodHandles

.findNative(null, “getpid”, intType);


return (int) handle.invokeExact();

}
Value Types
value class Point {

final int x;

final int y;

}



// Create a Point instance

Point point = makeValue(1, 2);
Value Types
int[] values = new int[2];

int x = values[0];

int y = values[1];
Value Types
int[] values = new int[2];

int x = values[0];

int y = values[1];
Stack
var X
var Y
Value Types
int[] values = new int[2];

int x = values[0];

int y = values[1];
Stack
var X
var Y
Stack Allocation!
Specialized Generics
class Box<any T> {

void set(T element) { ... };


T get() { ... };

}
Specialized Generics
class Box<any T> {

void set(T element) { ... };


T get() { ... };

}
Box<int> Box${T=int}.class

Box<String> Box${T=java.lang.String}.class

Box<RandomClass> Box${T=RandomClass}.class
Specialized Generics
public void generics() {

Box<int> intBox = new Box<>();

intBox.set(1);

int intValue = intBox.get();



Box<String> stringBox = new Box<>();

stringBox.set("hello");

String stringValue = stringBox.get();



Box<RandomClass> box = new Box<>();

box.set(new RandomClass());

RandomClass value = box.get();

}
Arrays 2.0
int[] values = new int[Long.MAX_VALUE];
Arrays 2.0
int[] values = new int[Long.MAX_VALUE];
Arrays.chop(T[] a, int newlength);
Arrays 2.0
int[] values = new int[Long.MAX_VALUE];
Arrays.chop(T[] a, int newlength);
Box<String>[] ... = new Box<String>[];
Arrays 2.0
int[] values = new int[Long.MAX_VALUE];
Arrays.chop(T[] a, int newlength);
Box<int>[] ... = new Box<int>[];
Arrays 2.0
int[] values = new int[Long.MAX_VALUE];
Arrays.chop(T[] a, int newlength);
Box<int>[] ... = new Box<int>[];
char[] frozen = new char[20L].freeze();
Arrays 2.0
int[] values = new int[Long.MAX_VALUE];
Arrays.chop(T[] a, int newlength);
Box<int>[] ... = new Box<int>[];
char[] frozen = new char[20L].freeze();
Point[] points = new Point[3]; Stack
var X
var Y
var X
var Y
var X
var Y
points[0]
points[1]
points[2]
Cleaner API
Who knows the Cleaner API?
You should - it’s around since Java 1.4 ;-)
Cleaner API
package java.nio;
import sun.misc.Cleaner;
class DirectByteBuffer

extends MappedByteBuffer

implements DirectBuffer {
private static class Deallocator implements Runnable {
private Deallocator(long address, long size, int capacity) {...}
public void run() {...}
}
private final Cleaner cleaner;
DirectByteBuffer(int cap) {
...
cleaner = Cleaner.create(this, new Deallocator(base, size, cap));
}
}
Cleaner API
public selfCleaning() {

try(AutoCleaning autoCleaning : new AutoCleaning()) {

// do your thing here

}

}
Cleaner API
public class AutoCleaning implements AutoCloseable {
// A cleaner, preferably one shared within a library
private static final Cleaner cleaner = ...;
static class State
implements Runnable {
State(...) {/* initialize State needed for cleaning action */}
public void run() {/*cleanup action accessing State, executed at most once*/}
}
private final State state;
private final Cleaner.Cleanable cleanable;
public AutoCleaning() {
this.state = new State(...);
this.cleanable = cleaner.register(this, state);
}
public void close() {
cleanable.clean();
}
}
More exciting
stuff upcoming…
Class Dynamic
Class Dynamic
•Templating functionality
Class Dynamic
•Templating functionality
•Aspect-like approach
Class Dynamic
•Templating functionality
•Aspect-like approach
•Group common functionality
Class Dynamic
•Templating functionality
•Aspect-like approach
•Group common functionality
•Enhanced Proxies
Class Dynamic
•Templating functionality
•Aspect-like approach
•Group common functionality
•Enhanced Proxies
R methodName(ARGS) {

synchronized (this) {

underlying.methodName(ARGS);

}

}
Collections::sychronizedMap
Class Dynamic
•Templating functionality
•Aspect-like approach
•Group common functionality
•Enhanced Proxies
Logging / Tracing
R methodName(ARGS) {

logger.trace("Before methodname X");
underlying.methodName(ARGS);

logger.trace("After methodname X");

}
Class Dynamic
•Templating functionality
•Aspect-like approach
•Group common functionality
•Enhanced Proxies
Your Use Case!
SpinWait Hints
SpinWait Hints
Hints the JVM that a busy spin’s upcoming
SpinWait Hints
Hints the JVM that a busy spin’s upcoming
JVM CAN intrinsify to use a WAIT opcode for the specific platform / CPU
SpinWait Hints
Hints the JVM that a busy spin’s upcoming
JVM CAN intrinsify to use a WAIT opcode for the specific platform / CPU
No-Op implementation for non supported CPUs
SpinWait Hints
Hints the JVM that a busy spin’s upcoming
JVM CAN intrinsify to use a WAIT opcode for the specific platform / CPU
No-Op implementation for non supported CPUs
while (!shutdown) {

while (queue.length == 0) {

// Hint the JVM to intrinsify wait

// opcode otherwise busy spin 

Thread.onSpinWait();

}

consume(queue);

}
What Else?
No idea!
A lot is changing now.
Java / JVM will be different.
What Else?
No idea!
A lot is changing now.
Java / JVM will be different.
Don’t forget about Jigsaw,
test your application with Java 9 EA builds!
https://jdk9.java.net/jigsaw/
Questions?
github.com/noctarius
@noctarius2k
More information:
• http://openjdk.java.net/jeps/193
• http://openjdk.java.net/jeps/254
• http://openjdk.java.net/jeps/285
• http://openjdk.java.net/projects/valhalla/
• http://cr.openjdk.java.net/~jrose/arrays/frozen-array-value-rules.html
• https://twitter.com/PaulSandoz/status/623891528432394240
• http://openjdk.java.net/projects/panama/
• http://cr.openjdk.java.net/~jrose/values/values-0.html
• http://cr.openjdk.java.net/~briangoetz/valhalla/spec-classdyn.html
• http://blog.codefx.org/java/dev/the-road-to-valhalla/
http://openjdk.java.net/jeps/259
http://openjdk.java.net/jeps/286
http://openjdk.java.net/jeps/276
http://openjdk.java.net/jeps/269
http://openjdk.java.net/jeps/266
http://openjdk.java.net/jeps/191
http://openjdk.java.net/jeps/186
http://openjdk.java.net/jeps/277

Contenu connexe

Tendances

Testing Multithreaded Java Applications for Synchronization Problems, ISTA 2011
Testing Multithreaded Java Applications for Synchronization Problems, ISTA 2011Testing Multithreaded Java Applications for Synchronization Problems, ISTA 2011
Testing Multithreaded Java Applications for Synchronization Problems, ISTA 2011Vassil Popovski
 
Guardians of your CODE
Guardians of your CODEGuardians of your CODE
Guardians of your CODEPeter Hlavaty
 
Power of linked list
Power of linked listPower of linked list
Power of linked listPeter Hlavaty
 
Automate Yo'self -- SeaGL
Automate Yo'self -- SeaGL Automate Yo'self -- SeaGL
Automate Yo'self -- SeaGL John Anderson
 
JRuby: What's Different (RORO Melbourne October 2011)
JRuby: What's Different (RORO Melbourne October 2011)JRuby: What's Different (RORO Melbourne October 2011)
JRuby: What's Different (RORO Melbourne October 2011)Charles Nutter
 
Testing multithreaded java applications for synchronization problems
Testing multithreaded java applications for synchronization problemsTesting multithreaded java applications for synchronization problems
Testing multithreaded java applications for synchronization problemsVassil Popovski
 
You didnt see it’s coming? "Dawn of hardened Windows Kernel"
You didnt see it’s coming? "Dawn of hardened Windows Kernel" You didnt see it’s coming? "Dawn of hardened Windows Kernel"
You didnt see it’s coming? "Dawn of hardened Windows Kernel" Peter Hlavaty
 
Ice Age melting down: Intel features considered usefull!
Ice Age melting down: Intel features considered usefull!Ice Age melting down: Intel features considered usefull!
Ice Age melting down: Intel features considered usefull!Peter Hlavaty
 
Vulnerability desing patterns
Vulnerability desing patternsVulnerability desing patterns
Vulnerability desing patternsPeter Hlavaty
 
Rainbow Over the Windows: More Colors Than You Could Expect
Rainbow Over the Windows: More Colors Than You Could ExpectRainbow Over the Windows: More Colors Than You Could Expect
Rainbow Over the Windows: More Colors Than You Could ExpectPeter Hlavaty
 
Metasepi team meeting #20: Start! ATS programming on MCU
Metasepi team meeting #20: Start! ATS programming on MCUMetasepi team meeting #20: Start! ATS programming on MCU
Metasepi team meeting #20: Start! ATS programming on MCUKiwamu Okabe
 
Infrastructure as code might be literally impossible part 2
Infrastructure as code might be literally impossible part 2Infrastructure as code might be literally impossible part 2
Infrastructure as code might be literally impossible part 2ice799
 
Functional IoT: Hardware and Platform
Functional IoT: Hardware and PlatformFunctional IoT: Hardware and Platform
Functional IoT: Hardware and PlatformKiwamu Okabe
 
Introduction to VeriFast @ Kyoto
Introduction to VeriFast @ KyotoIntroduction to VeriFast @ Kyoto
Introduction to VeriFast @ KyotoKiwamu Okabe
 
Digging for Android Kernel Bugs
Digging for Android Kernel BugsDigging for Android Kernel Bugs
Digging for Android Kernel BugsJiahong Fang
 

Tendances (20)

Testing Multithreaded Java Applications for Synchronization Problems, ISTA 2011
Testing Multithreaded Java Applications for Synchronization Problems, ISTA 2011Testing Multithreaded Java Applications for Synchronization Problems, ISTA 2011
Testing Multithreaded Java Applications for Synchronization Problems, ISTA 2011
 
Guardians of your CODE
Guardians of your CODEGuardians of your CODE
Guardians of your CODE
 
Power of linked list
Power of linked listPower of linked list
Power of linked list
 
Automate Yo'self -- SeaGL
Automate Yo'self -- SeaGL Automate Yo'self -- SeaGL
Automate Yo'self -- SeaGL
 
JRuby: What's Different (RORO Melbourne October 2011)
JRuby: What's Different (RORO Melbourne October 2011)JRuby: What's Different (RORO Melbourne October 2011)
JRuby: What's Different (RORO Melbourne October 2011)
 
Testing multithreaded java applications for synchronization problems
Testing multithreaded java applications for synchronization problemsTesting multithreaded java applications for synchronization problems
Testing multithreaded java applications for synchronization problems
 
EhTrace -- RoP Hooks
EhTrace -- RoP HooksEhTrace -- RoP Hooks
EhTrace -- RoP Hooks
 
Clojure presentation
Clojure presentationClojure presentation
Clojure presentation
 
You didnt see it’s coming? "Dawn of hardened Windows Kernel"
You didnt see it’s coming? "Dawn of hardened Windows Kernel" You didnt see it’s coming? "Dawn of hardened Windows Kernel"
You didnt see it’s coming? "Dawn of hardened Windows Kernel"
 
Ice Age melting down: Intel features considered usefull!
Ice Age melting down: Intel features considered usefull!Ice Age melting down: Intel features considered usefull!
Ice Age melting down: Intel features considered usefull!
 
Vulnerability desing patterns
Vulnerability desing patternsVulnerability desing patterns
Vulnerability desing patterns
 
Rainbow Over the Windows: More Colors Than You Could Expect
Rainbow Over the Windows: More Colors Than You Could ExpectRainbow Over the Windows: More Colors Than You Could Expect
Rainbow Over the Windows: More Colors Than You Could Expect
 
Metasepi team meeting #20: Start! ATS programming on MCU
Metasepi team meeting #20: Start! ATS programming on MCUMetasepi team meeting #20: Start! ATS programming on MCU
Metasepi team meeting #20: Start! ATS programming on MCU
 
Packers
PackersPackers
Packers
 
Infrastructure as code might be literally impossible part 2
Infrastructure as code might be literally impossible part 2Infrastructure as code might be literally impossible part 2
Infrastructure as code might be literally impossible part 2
 
Buffer Overflow Attacks
Buffer Overflow AttacksBuffer Overflow Attacks
Buffer Overflow Attacks
 
Functional IoT: Hardware and Platform
Functional IoT: Hardware and PlatformFunctional IoT: Hardware and Platform
Functional IoT: Hardware and Platform
 
RPM experiments
RPM experimentsRPM experiments
RPM experiments
 
Introduction to VeriFast @ Kyoto
Introduction to VeriFast @ KyotoIntroduction to VeriFast @ Kyoto
Introduction to VeriFast @ Kyoto
 
Digging for Android Kernel Bugs
Digging for Android Kernel BugsDigging for Android Kernel Bugs
Digging for Android Kernel Bugs
 

Similaire à A Post-Apocalyptic sun.misc.Unsafe World by Christoph engelbert

Jvm tuning in a rush! - Lviv JUG
Jvm tuning in a rush! - Lviv JUGJvm tuning in a rush! - Lviv JUG
Jvm tuning in a rush! - Lviv JUGTomek Borek
 
Rust Programming Language
Rust Programming LanguageRust Programming Language
Rust Programming LanguageJaeju Kim
 
GOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter SlidesGOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter SlidesAlexandra Masterson
 
Hacking Adobe Experience Manager sites
Hacking Adobe Experience Manager sitesHacking Adobe Experience Manager sites
Hacking Adobe Experience Manager sitesMikhail Egorov
 
Доклад Михаила Егорова на PHDays
Доклад Михаила Егорова на PHDaysДоклад Михаила Егорова на PHDays
Доклад Михаила Егорова на PHDaysru_Parallels
 
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...Hackito Ergo Sum
 
JavaOne 2010: Top 10 Causes for Java Issues in Production and What to Do When...
JavaOne 2010: Top 10 Causes for Java Issues in Production and What to Do When...JavaOne 2010: Top 10 Causes for Java Issues in Production and What to Do When...
JavaOne 2010: Top 10 Causes for Java Issues in Production and What to Do When...srisatish ambati
 
Geek out 2014-lagergren-final
Geek out 2014-lagergren-finalGeek out 2014-lagergren-final
Geek out 2014-lagergren-finalMarcus Lagergren
 
DEF CON 27 - ORANGE TSAI and MEH CHANG - infiltrating corporate intranet like...
DEF CON 27 - ORANGE TSAI and MEH CHANG - infiltrating corporate intranet like...DEF CON 27 - ORANGE TSAI and MEH CHANG - infiltrating corporate intranet like...
DEF CON 27 - ORANGE TSAI and MEH CHANG - infiltrating corporate intranet like...Felipe Prado
 
Lions, Tigers and Deers: What building zoos can teach us about securing micro...
Lions, Tigers and Deers: What building zoos can teach us about securing micro...Lions, Tigers and Deers: What building zoos can teach us about securing micro...
Lions, Tigers and Deers: What building zoos can teach us about securing micro...Sysdig
 
Docking postgres
Docking postgresDocking postgres
Docking postgresrycamor
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
From SaltStack to Puppet and beyond...
From SaltStack to Puppet and beyond...From SaltStack to Puppet and beyond...
From SaltStack to Puppet and beyond...Yury Bushmelev
 
Larson Macaulay apt_malware_past_present_future_out_of_band_techniques
Larson Macaulay apt_malware_past_present_future_out_of_band_techniquesLarson Macaulay apt_malware_past_present_future_out_of_band_techniques
Larson Macaulay apt_malware_past_present_future_out_of_band_techniquesScott K. Larson
 
Memory Management: What You Need to Know When Moving to Java 8
Memory Management: What You Need to Know When Moving to Java 8Memory Management: What You Need to Know When Moving to Java 8
Memory Management: What You Need to Know When Moving to Java 8AppDynamics
 
The State of Rootless Containers
The State of Rootless ContainersThe State of Rootless Containers
The State of Rootless ContainersAkihiro Suda
 
ContainerWorkloadwithSemeru.pdf
ContainerWorkloadwithSemeru.pdfContainerWorkloadwithSemeru.pdf
ContainerWorkloadwithSemeru.pdfSumanMitra22
 
Understanding container security
Understanding container securityUnderstanding container security
Understanding container securityJohn Kinsella
 
2013 syscan360 yuki_chen_syscan360_exploit your java native vulnerabilities o...
2013 syscan360 yuki_chen_syscan360_exploit your java native vulnerabilities o...2013 syscan360 yuki_chen_syscan360_exploit your java native vulnerabilities o...
2013 syscan360 yuki_chen_syscan360_exploit your java native vulnerabilities o...chen yuki
 

Similaire à A Post-Apocalyptic sun.misc.Unsafe World by Christoph engelbert (20)

Jvm tuning in a rush! - Lviv JUG
Jvm tuning in a rush! - Lviv JUGJvm tuning in a rush! - Lviv JUG
Jvm tuning in a rush! - Lviv JUG
 
Rust Programming Language
Rust Programming LanguageRust Programming Language
Rust Programming Language
 
GOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter SlidesGOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter Slides
 
Hacking Adobe Experience Manager sites
Hacking Adobe Experience Manager sitesHacking Adobe Experience Manager sites
Hacking Adobe Experience Manager sites
 
Доклад Михаила Егорова на PHDays
Доклад Михаила Егорова на PHDaysДоклад Михаила Егорова на PHDays
Доклад Михаила Егорова на PHDays
 
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
 
JavaOne 2010: Top 10 Causes for Java Issues in Production and What to Do When...
JavaOne 2010: Top 10 Causes for Java Issues in Production and What to Do When...JavaOne 2010: Top 10 Causes for Java Issues in Production and What to Do When...
JavaOne 2010: Top 10 Causes for Java Issues in Production and What to Do When...
 
Geek out 2014-lagergren-final
Geek out 2014-lagergren-finalGeek out 2014-lagergren-final
Geek out 2014-lagergren-final
 
DEF CON 27 - ORANGE TSAI and MEH CHANG - infiltrating corporate intranet like...
DEF CON 27 - ORANGE TSAI and MEH CHANG - infiltrating corporate intranet like...DEF CON 27 - ORANGE TSAI and MEH CHANG - infiltrating corporate intranet like...
DEF CON 27 - ORANGE TSAI and MEH CHANG - infiltrating corporate intranet like...
 
Lions, Tigers and Deers: What building zoos can teach us about securing micro...
Lions, Tigers and Deers: What building zoos can teach us about securing micro...Lions, Tigers and Deers: What building zoos can teach us about securing micro...
Lions, Tigers and Deers: What building zoos can teach us about securing micro...
 
Docking postgres
Docking postgresDocking postgres
Docking postgres
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
From SaltStack to Puppet and beyond...
From SaltStack to Puppet and beyond...From SaltStack to Puppet and beyond...
From SaltStack to Puppet and beyond...
 
Larson Macaulay apt_malware_past_present_future_out_of_band_techniques
Larson Macaulay apt_malware_past_present_future_out_of_band_techniquesLarson Macaulay apt_malware_past_present_future_out_of_band_techniques
Larson Macaulay apt_malware_past_present_future_out_of_band_techniques
 
Memory Management: What You Need to Know When Moving to Java 8
Memory Management: What You Need to Know When Moving to Java 8Memory Management: What You Need to Know When Moving to Java 8
Memory Management: What You Need to Know When Moving to Java 8
 
Java platform
Java platformJava platform
Java platform
 
The State of Rootless Containers
The State of Rootless ContainersThe State of Rootless Containers
The State of Rootless Containers
 
ContainerWorkloadwithSemeru.pdf
ContainerWorkloadwithSemeru.pdfContainerWorkloadwithSemeru.pdf
ContainerWorkloadwithSemeru.pdf
 
Understanding container security
Understanding container securityUnderstanding container security
Understanding container security
 
2013 syscan360 yuki_chen_syscan360_exploit your java native vulnerabilities o...
2013 syscan360 yuki_chen_syscan360_exploit your java native vulnerabilities o...2013 syscan360 yuki_chen_syscan360_exploit your java native vulnerabilities o...
2013 syscan360 yuki_chen_syscan360_exploit your java native vulnerabilities o...
 

Plus de J On The Beach

Massively scalable ETL in real world applications: the hard way
Massively scalable ETL in real world applications: the hard wayMassively scalable ETL in real world applications: the hard way
Massively scalable ETL in real world applications: the hard wayJ On The Beach
 
Big Data On Data You Don’t Have
Big Data On Data You Don’t HaveBig Data On Data You Don’t Have
Big Data On Data You Don’t HaveJ On The Beach
 
Acoustic Time Series in Industry 4.0: Improved Reliability and Cyber-Security...
Acoustic Time Series in Industry 4.0: Improved Reliability and Cyber-Security...Acoustic Time Series in Industry 4.0: Improved Reliability and Cyber-Security...
Acoustic Time Series in Industry 4.0: Improved Reliability and Cyber-Security...J On The Beach
 
Pushing it to the edge in IoT
Pushing it to the edge in IoTPushing it to the edge in IoT
Pushing it to the edge in IoTJ On The Beach
 
Drinking from the firehose, with virtual streams and virtual actors
Drinking from the firehose, with virtual streams and virtual actorsDrinking from the firehose, with virtual streams and virtual actors
Drinking from the firehose, with virtual streams and virtual actorsJ On The Beach
 
How do we deploy? From Punched cards to Immutable server pattern
How do we deploy? From Punched cards to Immutable server patternHow do we deploy? From Punched cards to Immutable server pattern
How do we deploy? From Punched cards to Immutable server patternJ On The Beach
 
When Cloud Native meets the Financial Sector
When Cloud Native meets the Financial SectorWhen Cloud Native meets the Financial Sector
When Cloud Native meets the Financial SectorJ On The Beach
 
The big data Universe. Literally.
The big data Universe. Literally.The big data Universe. Literally.
The big data Universe. Literally.J On The Beach
 
Streaming to a New Jakarta EE
Streaming to a New Jakarta EEStreaming to a New Jakarta EE
Streaming to a New Jakarta EEJ On The Beach
 
The TIPPSS Imperative for IoT - Ensuring Trust, Identity, Privacy, Protection...
The TIPPSS Imperative for IoT - Ensuring Trust, Identity, Privacy, Protection...The TIPPSS Imperative for IoT - Ensuring Trust, Identity, Privacy, Protection...
The TIPPSS Imperative for IoT - Ensuring Trust, Identity, Privacy, Protection...J On The Beach
 
Pushing AI to the Client with WebAssembly and Blazor
Pushing AI to the Client with WebAssembly and BlazorPushing AI to the Client with WebAssembly and Blazor
Pushing AI to the Client with WebAssembly and BlazorJ On The Beach
 
Axon Server went RAFTing
Axon Server went RAFTingAxon Server went RAFTing
Axon Server went RAFTingJ On The Beach
 
The Six Pitfalls of building a Microservices Architecture (and how to avoid t...
The Six Pitfalls of building a Microservices Architecture (and how to avoid t...The Six Pitfalls of building a Microservices Architecture (and how to avoid t...
The Six Pitfalls of building a Microservices Architecture (and how to avoid t...J On The Beach
 
Madaari : Ordering For The Monkeys
Madaari : Ordering For The MonkeysMadaari : Ordering For The Monkeys
Madaari : Ordering For The MonkeysJ On The Beach
 
Servers are doomed to fail
Servers are doomed to failServers are doomed to fail
Servers are doomed to failJ On The Beach
 
Interaction Protocols: It's all about good manners
Interaction Protocols: It's all about good mannersInteraction Protocols: It's all about good manners
Interaction Protocols: It's all about good mannersJ On The Beach
 
A race of two compilers: GraalVM JIT versus HotSpot JIT C2. Which one offers ...
A race of two compilers: GraalVM JIT versus HotSpot JIT C2. Which one offers ...A race of two compilers: GraalVM JIT versus HotSpot JIT C2. Which one offers ...
A race of two compilers: GraalVM JIT versus HotSpot JIT C2. Which one offers ...J On The Beach
 
Leadership at every level
Leadership at every levelLeadership at every level
Leadership at every levelJ On The Beach
 
Machine Learning: The Bare Math Behind Libraries
Machine Learning: The Bare Math Behind LibrariesMachine Learning: The Bare Math Behind Libraries
Machine Learning: The Bare Math Behind LibrariesJ On The Beach
 

Plus de J On The Beach (20)

Massively scalable ETL in real world applications: the hard way
Massively scalable ETL in real world applications: the hard wayMassively scalable ETL in real world applications: the hard way
Massively scalable ETL in real world applications: the hard way
 
Big Data On Data You Don’t Have
Big Data On Data You Don’t HaveBig Data On Data You Don’t Have
Big Data On Data You Don’t Have
 
Acoustic Time Series in Industry 4.0: Improved Reliability and Cyber-Security...
Acoustic Time Series in Industry 4.0: Improved Reliability and Cyber-Security...Acoustic Time Series in Industry 4.0: Improved Reliability and Cyber-Security...
Acoustic Time Series in Industry 4.0: Improved Reliability and Cyber-Security...
 
Pushing it to the edge in IoT
Pushing it to the edge in IoTPushing it to the edge in IoT
Pushing it to the edge in IoT
 
Drinking from the firehose, with virtual streams and virtual actors
Drinking from the firehose, with virtual streams and virtual actorsDrinking from the firehose, with virtual streams and virtual actors
Drinking from the firehose, with virtual streams and virtual actors
 
How do we deploy? From Punched cards to Immutable server pattern
How do we deploy? From Punched cards to Immutable server patternHow do we deploy? From Punched cards to Immutable server pattern
How do we deploy? From Punched cards to Immutable server pattern
 
Java, Turbocharged
Java, TurbochargedJava, Turbocharged
Java, Turbocharged
 
When Cloud Native meets the Financial Sector
When Cloud Native meets the Financial SectorWhen Cloud Native meets the Financial Sector
When Cloud Native meets the Financial Sector
 
The big data Universe. Literally.
The big data Universe. Literally.The big data Universe. Literally.
The big data Universe. Literally.
 
Streaming to a New Jakarta EE
Streaming to a New Jakarta EEStreaming to a New Jakarta EE
Streaming to a New Jakarta EE
 
The TIPPSS Imperative for IoT - Ensuring Trust, Identity, Privacy, Protection...
The TIPPSS Imperative for IoT - Ensuring Trust, Identity, Privacy, Protection...The TIPPSS Imperative for IoT - Ensuring Trust, Identity, Privacy, Protection...
The TIPPSS Imperative for IoT - Ensuring Trust, Identity, Privacy, Protection...
 
Pushing AI to the Client with WebAssembly and Blazor
Pushing AI to the Client with WebAssembly and BlazorPushing AI to the Client with WebAssembly and Blazor
Pushing AI to the Client with WebAssembly and Blazor
 
Axon Server went RAFTing
Axon Server went RAFTingAxon Server went RAFTing
Axon Server went RAFTing
 
The Six Pitfalls of building a Microservices Architecture (and how to avoid t...
The Six Pitfalls of building a Microservices Architecture (and how to avoid t...The Six Pitfalls of building a Microservices Architecture (and how to avoid t...
The Six Pitfalls of building a Microservices Architecture (and how to avoid t...
 
Madaari : Ordering For The Monkeys
Madaari : Ordering For The MonkeysMadaari : Ordering For The Monkeys
Madaari : Ordering For The Monkeys
 
Servers are doomed to fail
Servers are doomed to failServers are doomed to fail
Servers are doomed to fail
 
Interaction Protocols: It's all about good manners
Interaction Protocols: It's all about good mannersInteraction Protocols: It's all about good manners
Interaction Protocols: It's all about good manners
 
A race of two compilers: GraalVM JIT versus HotSpot JIT C2. Which one offers ...
A race of two compilers: GraalVM JIT versus HotSpot JIT C2. Which one offers ...A race of two compilers: GraalVM JIT versus HotSpot JIT C2. Which one offers ...
A race of two compilers: GraalVM JIT versus HotSpot JIT C2. Which one offers ...
 
Leadership at every level
Leadership at every levelLeadership at every level
Leadership at every level
 
Machine Learning: The Bare Math Behind Libraries
Machine Learning: The Bare Math Behind LibrariesMachine Learning: The Bare Math Behind Libraries
Machine Learning: The Bare Math Behind Libraries
 

Dernier

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 

Dernier (20)

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 

A Post-Apocalyptic sun.misc.Unsafe World by Christoph engelbert

  • 2. www.hazelcast.com@noctarius2k Who’s that dude? • Chris Engelbert • Manager Developer Relations @Hazelcast • Twitter-Senpai • Java-Passionist (10+ years) • Performance • Garbage Collection • Benchmark Fairytales
  • 3. Disclaimer This talk is not going to be negative!
  • 4. Disclaimer But certain things are highly speculative
 and APIs or ideas might change by tomorrow!
  • 6. sun.misc.Unsafe - What you (don’t) know
  • 7. sun.misc.Unsafe - What you (don’t) know • Internal class (sun.misc Package)
  • 8. sun.misc.Unsafe - What you (don’t) know • Internal class (sun.misc Package)
  • 9. sun.misc.Unsafe - What you (don’t) know • Internal class (sun.misc Package) • Used inside the JVM / JRE
  • 10. sun.misc.Unsafe - What you (don’t) know • Internal class (sun.misc Package) • Used inside the JVM / JRE // Unsafe mechanics
 private static final sun.misc.Unsafe U;
 private static final long QBASE;
 private static final long QLOCK;
 private static final int ABASE;
 private static final int ASHIFT;
 static {
 try {
 U = sun.misc.Unsafe.getUnsafe();
 Class<?> k = WorkQueue.class;
 Class<?> ak = ForkJoinTask[].class;
 QBASE = U.objectFieldOffset
 (k.getDeclaredField("base"));
 QLOCK = U.objectFieldOffset
 (k.getDeclaredField("qlock"));
 ABASE = U.arrayBaseOffset(ak);
 int scale = U.arrayIndexScale(ak);
 if ((scale & (scale - 1)) != 0)
 throw new Error("data type scale not a power of two");
 ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
 } catch (Exception e) {
 throw new Error(e);
 }
 }
 } example: java.util.concurrent.ForkJoinPool
  • 11. sun.misc.Unsafe - What you (don’t) know • Internal class (sun.misc Package) • Used inside the JVM / JRE • Used outside as well
  • 12. sun.misc.Unsafe - What you (don’t) know • Internal class (sun.misc Package) • Used inside the JVM / JRE • Used outside as well (good // Deserialization public Object readObject(InputStream is) {
 SomeType element = unsafe.allocateInstance(SomeType.class);
 element.deserializeValues(is);
 return element;
 }
  • 13. sun.misc.Unsafe - What you (don’t) know • Internal class (sun.misc Package) • Used inside the JVM / JRE • Used outside as well (good, bad)
  • 14.
  • 15.
  • 16.
  • 17. # # A fatal error has been detected by the Java Runtime Environment: # # SIGSEGV (0xb) at pc=0x00000001067314b5, pid=25244, tid=5891 # # JRE version: Java(TM) SE Runtime Environment (8.0_05-b13) (build 1.8.0_05-b13) # Java VM: Java HotSpot(TM) 64-Bit Server VM (25.5-b02 mixed mode bsd-amd64 compressed oops) # Problematic frame: # V [libjvm.dylib+0x5314b5] Unsafe_SetNativeAddress+0x36 # # An error report file with more information is saved as: # /Users/noctarius/git/hazelcast-only.idea/hs_err_pid25244.log # # If you would like to submit a bug report, please visit: # http://bugreport.sun.com/bugreport/crash.jsp #
  • 18. sun.misc.Unsafe - What you (don’t) know • Internal class (sun.misc Package) • Used inside the JVM / JRE • Used outside as well (good / bad) • Never intended for outside use
  • 19. sun.misc.Unsafe - What you (don’t) know • Internal class (sun.misc Package) • Used inside the JVM / JRE • Used outside as well (good / bad) • Never intended for outside use
  • 20. sun.misc.Unsafe - What you (don’t) know • Internal class (sun.misc Package) • Used inside the JVM / JRE • Used outside as well (good / bad) • Never intended for outside use • Used by popular: • Applications • Frameworks • Libraries
  • 21. MapDB Netty Hazelcast Cassandra Mockito EasyMock JMock Scala Spock Robolectric Grails Gson Neo4j Apache Ignite Apache Spark Apache Kafka Apache Wink Apache Storm Apache Flink Apache Continuum Zookeeper Dropwizard Metrics (AOP) Kryo Byte Buddy Hibernate Liquibase Spring Framework Ehcache OrientDB Chronicle Apache Hadoop Apache HBase GWT Disruptor JRuby AkkaAgrona Aeron Simple Binary Encoding XRebel Presto jol ActivePivot LWJGL XAP XStream CapLogic WildFly Infinispan
  • 22. MapDB Netty Hazelcast Cassandra Mockito EasyMock JMock Scala Spock Robolectric Grails Gson Neo4j Apache Ignite Apache Spark Apache Kafka Apache Wink Apache Storm Apache Flink Apache Continuum Zookeeper Dropwizard Metrics (AOP) Kryo Byte Buddy Hibernate Liquibase Spring Framework Ehcache OrientDB Chronicle Apache Hadoop Apache HBase GWT Disruptor JRuby AkkaAgrona Aeron Simple Binary Encoding XRebel Presto jol ActivePivot LWJGL XAP XStream CapLogic WildFly Infinispan
  • 23. sun.misc.Unsafe is only supported on HotSpot JVMs anyways, isn’t it?
  • 24. sun.misc.Unsafe is only supported on HotSpot JVMs anyways, isn’t it? No!
  • 25. Language URL sun.misc.Unsafe Avian C++ https://github.com/ReadyTalk/avian Yes BicaVM JavaScript https://github.com/nurv/BicaVM No Cacao C http://www.cacaojvm.org Yes Excelsior JVM C / C++ ? http://www.excelsiorjet.com Yes Dalvik / ART / Android C / C++ https://source.android.com/source/index.html Yes Graal mainly Java http://openjdk.java.net/projects/graal Yes GCJ C / C++ https://gcc.gnu.org/java Yes HaikuVM C http://haiku-vm.sourceforge.net No IBM J9 C / C++ ? http://www.ibm.com/developerworks/java/jdk/index.html Yes IcedTea C / C++ http://icedtea.classpath.org/wiki/Main_Page Yes IKVM.NET C# http://www.ikvm.net Yes Jamiga C https://sourceforge.net/projects/jamiga2 No JamVM C http://jamvm.sourceforge.net Yes JatoVM C http://jatovm.org Yes JikesRVM C microkernel, Java http://www.jikesrvm.org Yes JNode C microkernel, Java http://www.jnode.org Yes JVM.go Go https://github.com/zxh0/jvm.go Yes JX C http://www4.cs.fau.de/Projects/JX/index.html No Kaffe C https://github.com/kaffe/kaffe Yes NanoVM C http://harbaum.org/till/nanovm/index.shtml No OpenJDK / Oracle / Zulu C / C++ http://openjdk.java.net Yes RoboVM C / C++ / ObjC https://robovm.com Yes SAPJVM C / C++ ? http://help.sap.com/saphelp_nwce10/helpdata/en/47/ dc90b4ef17452289f9128b8c2bbd77/content.htm Yes Waratek Multitenant JVM C / C++ ? http://www.waratek.com Yes Zing JVM C / C++ ? https://www.azul.com/products/zing Yes
  • 26. Use Cases - The Good Ones!
  • 27. Use Cases - The Good Ones! • Low Latency, GC Overhead
  • 28. Use Cases - The Good Ones! • Low Latency, GC Overhead Caution: Overly simplified! Unsafe unsafe = findUnsafe();
 long baseAddress = unsafe.allocateMemory(8); 
 class Point {
 long offsetX = 0;
 long offsetY = 4;
 
 int getX(long baseAddress) { return unsafe.getInt(baseAddress + offsetX); } 
 int getY(long baseAddress) { return unsafe.getInt(baseAddress + offsetY); }
 }
  • 29. Use Cases - The Good Ones! • Low Latency, GC Overhead • Fast (de-)serialization
  • 30. Use Cases - The Good Ones! • Low Latency, GC Overhead • Fast (de-)serialization // Deserialization public Object readObject(InputStream is) {
 SomeType element = unsafe.allocateInstance(SomeType.class);
 element.deserializeValues(is);
 return element;
 }
  • 31. Use Cases - The Good Ones! • Low Latency, GC Overhead • Fast (de-)serialization • 64bit Memory regions
  • 32. Use Cases - The Good Ones! • Low Latency, GC Overhead • Fast (de-)serialization • 64bit Memory regions long baseAddress = unsafe.allocateMemory(Long.MAX_VALUE);
 unsafe.putInt(baseAddress + Long.MAX_VALUE - 4, Integer.MAX_VALUE);
  • 33. Use Cases - The Good Ones! • Low Latency, GC Overhead • Fast (de-)serialization • 64bit Memory regions • Atomic memory operations
  • 34. Use Cases - The Good Ones! • Low Latency, GC Overhead • Fast (de-)serialization • 64bit Memory regions • Atomic memory operations unsafe.compareAndSwapInt(this, offsetField, oldValue, newValue);
 unsafe.compareAndSwapLong(this, offsetField, oldValue, newValue);
 unsafe.compareAndSwapObject(this, offsetField, oldObject, newObject);
  • 35. Use Cases - The Good Ones! • Low Latency, GC Overhead • Fast (de-)serialization • 64bit Memory regions • Atomic memory operations • Efficient memory layout
  • 36. Use Cases - The Good Ones! • Low Latency, GC Overhead • Fast (de-)serialization • 64bit Memory regions • Atomic memory operations • Efficient memory layout class Point {
 long offsetX = 0;
 long offsetY = 4;
 } offsetX offsetY
  • 37. Use Cases - The Good Ones! • Low Latency, GC Overhead • Fast (de-)serialization • 64bit Memory regions • Atomic memory operations • Efficient memory layout • Fast field / memory access
  • 38. Use Cases - The Good Ones! • Low Latency, GC Overhead • Fast (de-)serialization • 64bit Memory regions • Atomic memory operations • Efficient memory layout • Fast field / memory access long versionFieldOffset = unsafe.objectFieldOffset(versionField);
 
 long version = unsafe.getLong(this, versionFieldOffset);
 
 unsafe.putLong(this, versionFieldOffset, 10L);
  • 39. Use Cases - The Good Ones! • Low Latency, GC Overhead • Fast (de-)serialization • 64bit Memory regions • Atomic memory operations • Efficient memory layout • Fast field / memory access • Access to array elements with volatile semantics
  • 40. Use Cases - The Good Ones! • Low Latency, GC Overhead • Fast (de-)serialization • 64bit Memory regions • Atomic memory operations • Efficient memory layout • Fast field / memory access • Access to array elements with volatile semantics long base = unsafe.arrayBaseOffset(int[].class);
 long index = unsafe.arrayIndexScale(int[].class);
 
 unsafe.getIntVolatile(array, base + (index * 3));
  • 41. Use Cases - The Good Ones! • Low Latency, GC Overhead • Fast (de-)serialization • 64bit Memory regions • Atomic memory operations • Efficient memory layout • Fast field / memory access • Access to array elements with volatile semantics • Custom memory fences
  • 42. Use Cases - The Good Ones! • Low Latency, GC Overhead • Fast (de-)serialization • 64bit Memory regions • Atomic memory operations • Efficient memory layout • Fast field / memory access • Access to array elements with volatile semantics • Custom memory fences unsafe.fullFence(); 
 unsafe.storeFence(); 
 unsafe.loadFence();
  • 43. Use Cases - The Good Ones! • Low Latency, GC Overhead • Fast (de-)serialization • 64bit Memory regions • Atomic memory operations • Efficient memory layout • Fast field / memory access • Access to array elements with volatile semantics • Custom memory fences • Fast interaction with native code
  • 44. Use Cases - The Good Ones! • Low Latency, GC Overhead • Fast (de-)serialization • 64bit Memory regions • Atomic memory operations • Efficient memory layout • Fast field / memory access • Access to array elements with volatile semantics • Custom memory fences • Fast interaction with native code long addr = unsafe.allocateMemory(50);
 copyBytes(addr, byteArray);
 nativeCall(addr);
  • 46. Get Access Easy One (not working outside the JRE / JDK) Unsafe unsafe = Unsafe.getUnsafe();
  • 47. Get Access The Ugly One private static final Unsafe UNSAFE;
 static {
 try {
 Field theUnsafeField = Unsafe.class.getDeclaredField("theUnsafe");
 theUnsafeField.setAccessible(true);
 UNSAFE = (Unsafe) theUnsafeField.get(Unsafe.class);
 
 } catch (Exception e) {
 // We need you! =(
 throw new Error(e);
 }
 }
  • 48. Get Access The Working One (at least for more than just HotSpot) private static Unsafe findUnsafe() {
 try {
 return Unsafe.getUnsafe();
 } catch (SecurityException se) {
 return AccessController.doPrivileged(new PrivilegedAction<Unsafe>() {
 @Override
 public Unsafe run() {
 try {
 Class<Unsafe> type = Unsafe.class;
 try {
 Field field = type.getDeclaredField("theUnsafe");
 field.setAccessible(true);
 return type.cast(field.get(type));
 
 } catch (Exception e) {
 for (Field field : type.getDeclaredFields()) {
 if (type.isAssignableFrom(field.getType())) {
 field.setAccessible(true);
 return type.cast(field.get(type));
 }
 }
 }
 } catch (Exception e) {
 throw new RuntimeException("Unsafe unavailable", e);
 }
 throw new RuntimeException("Unsafe unavailable");
 }
 });
 }
 }
  • 49. Get Access The Tricky One private static final Unsafe UNSAFE;
 static {
 try {
 Constructor<Unsafe> constructor = Unsafe.class.getDeclaredConstructor(); 
 constructor.setAccessible(true);
 UNSAFE = constructor.newInstance();
 
 } catch (Exception e) {
 // We need you! =(
 throw new Error(e);
 }
 }
  • 50. Get Access Does Any Of This Feel Right?
  • 53. Let me be blunt -- sun.misc.Unsafe must die in a fire. It is -- wait for it -- Unsafe. It must go. Ignore any kind of theoretical rope and start the path to righteousness _*/now/*_. It is still years until the end of public updates to JDK 8, so we have /*years */to work this out properly. But sticking our heads in the collective sands and hoping for trivial work arounds to Unsafe is not going to work. If you're using Unsafe, this is the year to explain where the API is broken and get it straight.... Please help us kill Unsafe, kill Unsafe dead, kill Unsafe right, and do so as quickly as possible to the ultimate benefit of everyone. Wed Apr 8 19:15:42 UTC 2015, OpenJFX Mailinglist, Donald Smith, Oracle http://mail.openjdk.java.net/pipermail/openjfx-dev/2015-April/017028.html
  • 54. Let me be blunt -- sun.misc.Unsafe must die in a fire. It is -- wait for it -- Unsafe. It must go. Ignore any kind of theoretical rope and start the path to righteousness _*/now/*_. It is still years until the end of public updates to JDK 8, so we have /*years */to work this out properly. But sticking our heads in the collective sands and hoping for trivial work arounds to Unsafe is not going to work. If you're using Unsafe, this is the year to explain where the API is broken and get it straight.... Please help us kill Unsafe, kill Unsafe dead, kill Unsafe right, and do so as quickly as possible to the ultimate benefit of everyone. Wed Apr 8 19:15:42 UTC 2015, OpenJFX Mailinglist, Donald Smith, Oracle http://mail.openjdk.java.net/pipermail/openjfx-dev/2015-April/017028.html
  • 55. Let me be blunt -- sun.misc.Unsafe must die in a fire. It is -- wait for it -- Unsafe. It must go. Ignore any kind of theoretical rope and start the path to righteousness _*/now/*_. It is still years until the end of public updates to JDK 8, so we have /*years */to work this out properly. But sticking our heads in the collective sands and hoping for trivial work arounds to Unsafe is not going to work. If you're using Unsafe, this is the year to explain where the API is broken and get it straight.... Please help us kill Unsafe, kill Unsafe dead, kill Unsafe right, and do so as quickly as possible to the ultimate benefit of everyone. Wed Apr 8 19:15:42 UTC 2015, OpenJFX Mailinglist, Donald Smith, Oracle http://mail.openjdk.java.net/pipermail/openjfx-dev/2015-April/017028.html
  • 56. Let me be blunt -- sun.misc.Unsafe must die in a fire. It is -- wait for it -- Unsafe. It must go. Ignore any kind of theoretical rope and start the path to righteousness _*/now/*_. It is still years until the end of public updates to JDK 8, so we have /*years */to work this out properly. But sticking our heads in the collective sands and hoping for trivial work arounds to Unsafe is not going to work. If you're using Unsafe, this is the year to explain where the API is broken and get it straight.... Please help us kill Unsafe, kill Unsafe dead, kill Unsafe right, and do so as quickly as possible to the ultimate benefit of everyone. Wed Apr 8 19:15:42 UTC 2015, OpenJFX Mailinglist, Donald Smith, Oracle http://mail.openjdk.java.net/pipermail/openjfx-dev/2015-April/017028.html
  • 57. Oracle created a new Taskforce
  • 58. Oracle created a new Taskforce K.U.T.T. - Kill Unsafe To Total death
  • 59. Let me be blunt -- sun.misc.Unsafe must die in a fire. It is -- wait for it -- Unsafe. It must go. Ignore any kind of theoretical rope and start the path to righteousness _*/now/*_. It is still years until the end of public updates to JDK 8, so we have /*years */to work this out properly. But sticking our heads in the collective sands and hoping for trivial work arounds to Unsafe is not going to work. If you're using Unsafe, this is the year to explain where the API is broken and get it straight.... Please help us kill Unsafe, kill Unsafe dead, kill Unsafe right, and do so as quickly as possible to the ultimate benefit of everyone. Wed Apr 8 19:15:42 UTC 2015, OpenJFX Mailinglist, Donald Smith, Oracle http://mail.openjdk.java.net/pipermail/openjfx-dev/2015-April/017028.html
  • 61. private static final Unsafe UNSAFE = findUnsafe(); private static long VERSION_OFFSET = findVersionOffset(); // Updated through Unsafe only! private volatile long version = 0; public long increment() { while(true) { long version = this.version; long newVersion = version + 1; if (UNSAFE.compareAndSwapLong( this, VERSION_OFFSET, version, newVersion)) { return newVersion; } } } Atomic Updates
  • 62. Atomic Updates private final AtomicLong version = new AtomicLong(0); public long increment() { return version.incrementAndGet(); }
  • 63. Atomic Updates private static final AtomicLongFieldUpdater<Record> VERSION =
 AtomicLongFieldUpdater.newUpdater(Record, "version");
 // Updated through atomic field updater only!
 private volatile long version = 0;
 
 public long increment() {
 return VERSION.incrementAndGet(this);
 }
  • 64. Atomic Updates private static final VarHandle VERSION = findVersionVarHandle();
 
 // Updated through VarHandle only!
 private volatile long version = 0;
 
 public long increment() {
 return (long) VERSION.addAndGet(this, 1);
 }
  • 65. Atomic Updates public static VarHandle findVersionVarHandle() {
 try {
 return MethodHandles.lookup().
 findFieldVarHandle(Record.class, "version", long.class);
 
 } catch (Exception e) {
 throw new Error(e);
 }
 }
  • 66. Memory Management public long memory() {
 long address = UNSAFE.allocateMemory(8); 
 UNSAFE.putLong(address, Long.MAX_VALUE); 
 return UNSAFE.getLong(address);
 }
  • 67. Memory Management public long memory() {
 ByteBuffer byteBuffer = ByteBuffer.allocateDirect(8);
 
 byteBuffer.putLong(0, Long.MAX_VALUE);
 
 return byteBuffer.getLong(0);
 }
  • 68. Memory Management public long memory() {
 ByteBuffer byteBuffer = ByteBuffer.allocateDirect(8);
 
 VarHandle bufferView =
 MethodHandles.byteBufferViewVarHandle(long[].class, true);
 
 bufferView.set(byteBuffer, 0, Long.MAX_VALUE);
 
 return bufferView.get(byteBuffer, 0);
 }
  • 69. Memory Management public long memory() {
 MemoryRegion region = MemoryRegion.allocateNative
 ("myname", MemoryRegion.UNALIGNED, Long.MAX_VALUE);
 
 VarHandle regionView = MethodHandles.
 memoryRegionViewVarHandle(long[].class, true); 
 regionView.set(region, 0, Long.MAX_VALUE); 
 return regionView.get(region, 0);
 }
  • 70. Memory Management public long memory() {
 MemoryRegion region = MemoryRegion.allocateNative
 ("myname", MemoryRegion.UNALIGNED, Long.MAX_VALUE);
 
 VarHandle regionView = MethodHandles.
 memoryRegionViewVarHandle(long[].class, true); 
 regionView.set(region, 0, Long.MAX_VALUE); 
 return regionView.get(region, 0);
 }
  • 71. Memory Management public long memory(long index) {
 try (Scope scope = new NativeScope()) {
 Pointer<Long> ptr = scope.allocate(
 NativeLibrary.createLayout(long.class), numElements);
 
 Reference<Long> ref = ptr.offset(index).deref();
 
 ref.set(Long.MAX_VALUE);
 
 return ref.get();
 }
 }
  • 73. Deserialization private static final Unsafe UNSAFE = findUnsafe();
 
 private static final long VALUE_OFFSET = findValueOffset();
 
 public String deserializeString() throws Exception {
 char[] chars = readCharsFromStream();
 String allocated = (String) UNSAFE.allocateInstance(String.class);
 UNSAFE.putObjectVolatile(allocated, VALUE_OFFSET, chars);
 return allocated;
 }
  • 74. Deserialization public String deserializeString() throws Exception {
 char[] chars = readCharsFromStream().freeze();
 
 ReflectionFactory reflectionFactory =
 ReflectionFactory.getReflectionFactory();
 
 Constructor<String> constructor = reflectionFactory
 .newConstructorForSerialization(String.class, char[].class);
 
 return constructor.newInstance(chars);
 }
  • 75. Interoperability extern c {
 JNIEXPORT int JNICALL
 Java_ProcessIdentifier_getProcessId(JNIEnv *, jobject);
 }
 
 JNIEXPORT int JNICALL
 Java_ProcessIdentifier_getProcessId(JNIEnv *env, jobject thisObj) {
 return getpid();
 }
 
 public class ProcessIdentifier {
 static {
 System.loadLibrary("processidentifier");
 }
 
 public native void talk();
 }
  • 76. Interoperability interface LibC {
 void getpid();
 }
 
 public int call() {
 LibC c = LibraryLoader.create(LibC.class).load("c");
 return c.getpid();
 }
  • 77. Interoperability public void call() { MethodType intType = MethodType.methodType(int.class); 
 MethodHandle handle = MethodHandles
 .findNative(null, “getpid”, intType); 
 return (int) handle.invokeExact();
 }
  • 78. Value Types value class Point {
 final int x;
 final int y;
 }
 
 // Create a Point instance
 Point point = makeValue(1, 2);
  • 79. Value Types int[] values = new int[2];
 int x = values[0];
 int y = values[1];
  • 80. Value Types int[] values = new int[2];
 int x = values[0];
 int y = values[1]; Stack var X var Y
  • 81. Value Types int[] values = new int[2];
 int x = values[0];
 int y = values[1]; Stack var X var Y Stack Allocation!
  • 82. Specialized Generics class Box<any T> {
 void set(T element) { ... }; 
 T get() { ... };
 }
  • 83. Specialized Generics class Box<any T> {
 void set(T element) { ... }; 
 T get() { ... };
 } Box<int> Box${T=int}.class
 Box<String> Box${T=java.lang.String}.class
 Box<RandomClass> Box${T=RandomClass}.class
  • 84. Specialized Generics public void generics() {
 Box<int> intBox = new Box<>();
 intBox.set(1);
 int intValue = intBox.get();
 
 Box<String> stringBox = new Box<>();
 stringBox.set("hello");
 String stringValue = stringBox.get();
 
 Box<RandomClass> box = new Box<>();
 box.set(new RandomClass());
 RandomClass value = box.get();
 }
  • 85. Arrays 2.0 int[] values = new int[Long.MAX_VALUE];
  • 86. Arrays 2.0 int[] values = new int[Long.MAX_VALUE]; Arrays.chop(T[] a, int newlength);
  • 87. Arrays 2.0 int[] values = new int[Long.MAX_VALUE]; Arrays.chop(T[] a, int newlength); Box<String>[] ... = new Box<String>[];
  • 88. Arrays 2.0 int[] values = new int[Long.MAX_VALUE]; Arrays.chop(T[] a, int newlength); Box<int>[] ... = new Box<int>[];
  • 89. Arrays 2.0 int[] values = new int[Long.MAX_VALUE]; Arrays.chop(T[] a, int newlength); Box<int>[] ... = new Box<int>[]; char[] frozen = new char[20L].freeze();
  • 90. Arrays 2.0 int[] values = new int[Long.MAX_VALUE]; Arrays.chop(T[] a, int newlength); Box<int>[] ... = new Box<int>[]; char[] frozen = new char[20L].freeze(); Point[] points = new Point[3]; Stack var X var Y var X var Y var X var Y points[0] points[1] points[2]
  • 91. Cleaner API Who knows the Cleaner API? You should - it’s around since Java 1.4 ;-)
  • 92. Cleaner API package java.nio; import sun.misc.Cleaner; class DirectByteBuffer
 extends MappedByteBuffer
 implements DirectBuffer { private static class Deallocator implements Runnable { private Deallocator(long address, long size, int capacity) {...} public void run() {...} } private final Cleaner cleaner; DirectByteBuffer(int cap) { ... cleaner = Cleaner.create(this, new Deallocator(base, size, cap)); } }
  • 93. Cleaner API public selfCleaning() {
 try(AutoCleaning autoCleaning : new AutoCleaning()) {
 // do your thing here
 }
 }
  • 94. Cleaner API public class AutoCleaning implements AutoCloseable { // A cleaner, preferably one shared within a library private static final Cleaner cleaner = ...; static class State implements Runnable { State(...) {/* initialize State needed for cleaning action */} public void run() {/*cleanup action accessing State, executed at most once*/} } private final State state; private final Cleaner.Cleanable cleanable; public AutoCleaning() { this.state = new State(...); this.cleanable = cleaner.register(this, state); } public void close() { cleanable.clean(); } }
  • 99. Class Dynamic •Templating functionality •Aspect-like approach •Group common functionality
  • 100. Class Dynamic •Templating functionality •Aspect-like approach •Group common functionality •Enhanced Proxies
  • 101. Class Dynamic •Templating functionality •Aspect-like approach •Group common functionality •Enhanced Proxies R methodName(ARGS) {
 synchronized (this) {
 underlying.methodName(ARGS);
 }
 } Collections::sychronizedMap
  • 102. Class Dynamic •Templating functionality •Aspect-like approach •Group common functionality •Enhanced Proxies Logging / Tracing R methodName(ARGS) {
 logger.trace("Before methodname X"); underlying.methodName(ARGS);
 logger.trace("After methodname X");
 }
  • 103. Class Dynamic •Templating functionality •Aspect-like approach •Group common functionality •Enhanced Proxies Your Use Case!
  • 105. SpinWait Hints Hints the JVM that a busy spin’s upcoming
  • 106. SpinWait Hints Hints the JVM that a busy spin’s upcoming JVM CAN intrinsify to use a WAIT opcode for the specific platform / CPU
  • 107. SpinWait Hints Hints the JVM that a busy spin’s upcoming JVM CAN intrinsify to use a WAIT opcode for the specific platform / CPU No-Op implementation for non supported CPUs
  • 108. SpinWait Hints Hints the JVM that a busy spin’s upcoming JVM CAN intrinsify to use a WAIT opcode for the specific platform / CPU No-Op implementation for non supported CPUs while (!shutdown) {
 while (queue.length == 0) {
 // Hint the JVM to intrinsify wait
 // opcode otherwise busy spin 
 Thread.onSpinWait();
 }
 consume(queue);
 }
  • 109. What Else? No idea! A lot is changing now. Java / JVM will be different.
  • 110. What Else? No idea! A lot is changing now. Java / JVM will be different. Don’t forget about Jigsaw, test your application with Java 9 EA builds! https://jdk9.java.net/jigsaw/
  • 111. Questions? github.com/noctarius @noctarius2k More information: • http://openjdk.java.net/jeps/193 • http://openjdk.java.net/jeps/254 • http://openjdk.java.net/jeps/285 • http://openjdk.java.net/projects/valhalla/ • http://cr.openjdk.java.net/~jrose/arrays/frozen-array-value-rules.html • https://twitter.com/PaulSandoz/status/623891528432394240 • http://openjdk.java.net/projects/panama/ • http://cr.openjdk.java.net/~jrose/values/values-0.html • http://cr.openjdk.java.net/~briangoetz/valhalla/spec-classdyn.html • http://blog.codefx.org/java/dev/the-road-to-valhalla/
  • 112.