jeudi 20 août 2015

IntStream from Random and Random concurrency

Is it safe to use the same Random instance to generate a stream (or parallel stream) and to influence that stream in one of its parts?

Consider the code below. The same gen is used to generate a parallel IntStream and to generate a random space every few chars. It runs and completes successfully, no exception thrown.

But is this code thread safe? It appears it is, because there are no invalid (out of range) character values. I think I should be corrupting Random's internal data, but apparently that's not the case. Why?

public class RandomGenTest {

    Random gen = new Random();

    String getRandomText(int len, double spaceProb) {
        return gen.ints('a', 'z').parallel()
                    .limit(len)
                    .mapToObj( i -> new Character(gen.nextDouble()<spaceProb?' ':(char)i))
                    .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString();
    }

    @Test
    public void test() {
        for (int a=10000; a<10000000; a*=2) {
            String text = getRandomText(a, .2);
            Assert.assertTrue(text.length() == text.chars().filter(c -> ((c>='a' && c<='z') || c==' ')).count());
        }
    }

}




Aucun commentaire:

Enregistrer un commentaire