Created
June 12, 2016 21:51
-
-
Save sureshg/f2b0d2716dfbd652d06d2e7760bfabd7 to your computer and use it in GitHub Desktop.
Java Memory Model Tests
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
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