Skip to content

Instantly share code, notes, and snippets.

@nipafx
Created May 3, 2016 10:03
Show Gist options
  • Save nipafx/42f8f30295068204cea734871e20309c to your computer and use it in GitHub Desktop.
Save nipafx/42f8f30295068204cea734871e20309c to your computer and use it in GitHub Desktop.
Exposing partially constructed instances
public class Reordering {
private static Constructed constructed;
public static void main(String[] args) throws Exception {
new Thread(Reordering::constructForever).start();
Thread.sleep(100);
checkInitializationUntilFails();
}
private static void constructForever() {
while (true) {
constructed = new Constructed();
}
}
private static void checkInitializationUntilFails() {
while (true) {
if (!constructed.initialized) {
throw new IllegalStateException();
}
}
}
private static class Constructed {
private boolean initialized;
public Constructed() {
initialized = true;
}
}
}
@nipafx
Copy link
Author

nipafx commented May 3, 2016

This doesn't work. But if you do what professionals do, it does.

For future reference:

  • get jcstress
    • hg clone http://hg.openjdk.java.net/code-tools/jcstress/ jcstress
    • cd jcstress/
    • mvn clean install -pl tests-custom -am
  • execute UnsafePublication:
    • java -XX:-UseCompressedOops -jar tests-custom/target/jcstress.jar -t .*UnsafePublication.* -v

My results:

 (ETA:        n/a) (R: 0.00E+00) (T:   1/0) (F: 1/1) (I: 1/5)       [OK] o.o.j.t.unsafe.UnsafePublication
  Observed state   Occurrences   Expectation  Interpretation                                              
            [-1]   120,403,564    ACCEPTABLE  The object is not yet published                             
             [0]           549    ACCEPTABLE  The object is published, but all fields are 0.              
             [1]         1,766    ACCEPTABLE  The object is published, at least 1 field is visible.       
             [2]         1,908    ACCEPTABLE  The object is published, at least 2 fields are visible.     
             [3]         3,751    ACCEPTABLE  The object is published, at least 3 fields are visible.     
             [4]     4,185,752    ACCEPTABLE  The object is published, all fields are visible.            

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment