Skip to content

Instantly share code, notes, and snippets.

@sureshg
Created June 12, 2016 21:51
Show Gist options
  • Save sureshg/f2b0d2716dfbd652d06d2e7760bfabd7 to your computer and use it in GitHub Desktop.
Save sureshg/f2b0d2716dfbd652d06d2e7760bfabd7 to your computer and use it in GitHub Desktop.
Java Memory Model Tests
class DataRace {
// Make volatile
boolean ready = false;
int answer = 0;
void thread1() {
// Spin Lock
while(!ready);
assert answer == 42
}
void thread2() {
answer = 42;
ready = true
}
}
/**
* Double checked locking.
*/
class DoubleChecked {
static volatile DoubleChecked instance;
static DoubleChecked getInstance() {
// Lazy initialization
if(instance ==null) {
synchronized(DoubleChecked.class) {
if(instance == null) {
instance = new DoubleChecked();
}
}
}
}
int foo = 0;
DoubleChecked() { foo = 42; }
void method() {
assert foo == 42;
}
}
// AtomicIntegerArray
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment