jne
jne

Reputation: 467

Why different result each run?

I'm playing around with CompletableFuture and streams in Java 8 and I get different printouts each time I run this. Just curious, why?

public class DoIt {
public static class My {
    private long cur = 0;
    public long next() {
        return cur++;
    }
}
public static long add() {
    long sum = 0;
    for (long i=0; i<=100;i++) {
        sum += i;
    }
    return sum;
}

public static long getResult(CompletableFuture<Long> f) {
    long l = 0;
    try {
        f.complete(42l);
        l = f.get();
        System.out.println(l);
    } catch (Exception e) {
        //...
    }
    return l;
}
public static void main(String[] args){
    ExecutorService exec = Executors.newFixedThreadPool(2);
    My my = new My();
    long sum = Stream.generate(my::next).limit(20000).
    map(x -> CompletableFuture.supplyAsync(()-> add(), exec)).
    mapToLong(f->getResult(f)).sum();
    System.out.println(sum);
    exec.shutdown();
}
}

If I skip the f.complete(42l) call I always get the same result.

Upvotes: 1

Views: 119

Answers (1)

aepurniet
aepurniet

Reputation: 1727

http://download.java.net/jdk8/docs/api/java/util/concurrent/CompletableFuture.html#complete-T-

by the time the complete(42l) call happens, some add()'s may have already completed.

Upvotes: 1

Related Questions