Created
December 20, 2011 18:02
-
-
Save elazarl/1502541 to your computer and use it in GitHub Desktop.
Trying to recreate the "Holder" class publishing error from JCIP.
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
/** | |
* Trying to recreate the "Holder" class publishing error from JCIP. | |
* See http://stackoverflow.com/a/6812936/55094 for the description of the problem. | |
*/ | |
public class Publishing { | |
static class Holder { | |
int h = 0; | |
int dummy = 0; | |
public Holder(int h) { | |
for (long i=0;i<1000*1000;i++) { | |
dummy += i*(-1+(i%2*2)); | |
} | |
this.h = h; | |
} | |
public int verifyNonZero() { | |
return 1/h; | |
} | |
} | |
static Holder holder = new Holder(1); | |
static class Publisher extends Thread { | |
@Override | |
public void run() { | |
for (long i=0;i<1000*1000;i++) { | |
holder = new Holder(100); | |
// Uncomment to verify execution of threads indeed interleaves | |
// if (i%10000 == 0) System.out.println("+"); | |
} | |
} | |
} | |
static class Verifier extends Thread { | |
@Override | |
public void run() { | |
for (long i=0;i<1000*1000;i++) { | |
holder.verifyNonZero(); | |
// if (i%10000 == 0) System.out.println("."); | |
} | |
} | |
} | |
public static void main(String[] argv) { | |
final int NTHREADS = 1000; | |
Thread[] publishers = new Thread[NTHREADS]; | |
Thread[] verifiers = new Thread[NTHREADS]; | |
for (int i=0;i<NTHREADS;i++) { | |
publishers[i] = new Publisher(); | |
verifiers[i] = new Verifier(); | |
} | |
for (int i=0;i<NTHREADS;i++) { | |
publishers[i].start(); | |
verifiers[i].start(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment