package class9_2_MemoryBarriers_start;// Dr. Yoder. MSOE. 11 May 2017 public class MemoryBarrierOnePrime { public static void main(String[] args) { new MemoryBarrierOnePrime().run(); } private boolean isFound = false; private long currentPrime = 0; private void run() { new Thread(this::findPrimes).start(); while(true) { while (!isFound) { /* busy-wait */ } System.out.println("A prime was found!"); System.out.println("prime = " + currentPrime); } } public void findPrimes() { for (long candidate = 100000000; candidate < Long.MAX_VALUE; candidate++) { if (isPrime(candidate)) { if(!isFound) { isFound = true; currentPrime = candidate; System.out.println("A prime was foud: " + currentPrime); } } } } /** * Slow O((2^b)) or worse algorithm (where b is the number of bits in candidate) * * TODO: Implement Miller-Rabin Primality test to get O(n^12) or better performance. * http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test * (Why nine characters for one dash? * Unicode character Oct Dec Hex HTML * en dash 020023 8211 0x2013 – ) * * @param candidate candidate to test * @return true if candidate is prime. */ private boolean isPrime(long candidate) { boolean isPrime = true; for(int divisor = 2; divisor < candidate && isPrime; divisor++) { if(candidate % divisor == 0) { isPrime = false; } } return isPrime; } }