dimanche 19 novembre 2017

Marsaglia's XorShift compareAndSet Thread safety

I have some problems to make a safety PRNG (Marsaglia's XorShift), in theory the serie of values generated have to be the same for each execution. But it's not my case and don't know why. I have to use compareAndSetfor the Thread Safety.

Thank you in advance for your help.

package fr.umlv.conc;

import java.util.concurrent.atomic.AtomicLong;

public class RandomTest {
  private AtomicLong z = new AtomicLong();

  public RandomTest(long seed) {
    if (seed == 0) {
      throw new IllegalArgumentException("seed == 0");
    }
    this.z = new AtomicLong(seed);
  }

  public long next() {
      // Marsaglia's XorShift
      AtomicLong seed = this.z;
      long oldseed, nextseed;
      do {
            oldseed = seed.get();
            nextseed = xorShift(oldseed);
          } while (!seed.compareAndSet(oldseed, nextseed));
    return nextseed * 2685821657736338717L;
  }

private long xorShift(long x) {
    x ^= x >>> 12;
    x ^= x << 25;
    x ^= x >>> 27;

    return x;
}

  public static void main(String[] args) {
        for(int i=0; i < 3; i++) {
            Thread t = new Thread(() -> {
                 RandomTest rng = new RandomTest(1);
                 for(int j = 0; j < 5_000; j++) {
                     System.out.println(rng.next());
                 }
            });
            t.start();
        }
  }
}




Aucun commentaire:

Enregistrer un commentaire