Skip to content

Instantly share code, notes, and snippets.

@nitsanw
Last active December 12, 2015 10:19
Show Gist options
  • Save nitsanw/4758225 to your computer and use it in GitHub Desktop.
Save nitsanw/4758225 to your computer and use it in GitHub Desktop.
Unaligned memory concurrent access atomicity test
public class DirectByteBufferUnalignedInLineAtomicityTests {
public abstract static class ByteBufferTest implements
Actor1_Effector1_Test<ByteBuffer, long[]> {
@Override
public ByteBuffer newState() {
return allocateNaughtyBuffer(getSize());
}
abstract int getSize();
@Override
public long[] newResult() {
return new long[1];
}
}
public static class LongTest extends ByteBufferTest {
int getSize() {
return 8;
}
@Override
public void effector1(ByteBuffer b) {
b.putLong(0, -1L);
}
@Override
public void actor1(ByteBuffer b, long[] r) {
r[0] = b.getLong(0);
}
}
private static final Random RANDOM = new Random();
public static ByteBuffer allocateNaughtyBuffer(int size) {
ByteBuffer buffy = allocateAlignedByteBuffer(CACHE_LINE_SIZE, CACHE_LINE_SIZE);
// new position is always unaligned for a type of size
int newPosition = (RANDOM.nextInt(CACHE_LINE_SIZE / size - 2)) * size
+ 1 + ((size > 2) ? RANDOM.nextInt(size - 2) : 0);
buffy.position(newPosition);
return buffy.slice().order(ByteOrder.nativeOrder());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment