Created
February 25, 2014 10:35
Shallow copy, bad idea
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static Object shallowCopy(Object obj) { | |
long size = sizeOf(obj); | |
long start = toAddress(obj); | |
long address = getUnsafe().allocateMemory(size); | |
getUnsafe().copyMemory(start, address, size); | |
return fromAddress(address); | |
} | |
static long toAddress(Object obj) { | |
Object[] array = new Object[] {obj}; | |
long baseOffset = getUnsafe().arrayBaseOffset(Object[].class); | |
return normalize(getUnsafe().getInt(array, baseOffset)); | |
} | |
static Object fromAddress(long address) { | |
Object[] array = new Object[] {null}; | |
long baseOffset = getUnsafe().arrayBaseOffset(Object[].class); | |
getUnsafe().putLong(array, baseOffset, address); | |
return array[0]; | |
} | |
static long sizeOf(Object object){ | |
return getUnsafe().getAddress( | |
normalize(getUnsafe().getInt(object, 4L)) + 12L); | |
} | |
static long normalize(int value) { | |
if(value >= 0) return value; | |
return (~0L >>> 32) & value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment