Path: csiph.com!news.swapon.de!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Steven Simpson Newsgroups: comp.lang.java.programmer Subject: Re: parallel stream with return Date: Wed, 30 Sep 2015 22:25:55 +0100 Organization: A noiseless patient Spider Lines: 84 Message-ID: <3k0udc-4m6.ln1@s.simpson148.btinternet.com> References: <2b9115f7-1b42-4ee4-9af9-1c8aa84f94d1@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=windows-1252; format=flowed Content-Transfer-Encoding: 7bit Injection-Info: mx02.eternal-september.org; posting-host="67a4ebbab48506afb3b9562f935faf8f"; logging-data="16914"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18rpez+Y65t4seV2fbagEH0A/C6ouNp1dk=" User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Thunderbird/38.2.0 In-Reply-To: Cancel-Lock: sha1:puK1xIaCAia/93d8HpJF5Qn+3UE= Xref: csiph.com comp.lang.java.programmer:32742 On 30/09/15 18:22, Eric Sosman wrote: > Untested: > > Set x = > IntStream.range(0, value) > .parallel() > .mapToObj(i -> this.generate()) > .collect(Collectors.toSet()); > > Note that this won't necessarily produce a HashSet, but is more > likely to produce some other kind of Set. If you really need an > actual HashSet, you could > > - Use the toCollection() method of Collectors import java.util.*; import java.util.function.*; import java.util.stream.*; public class Slop { private static Object generate() { return new Object(); } public static void main(String[] args) throws Exception { Collection foo = IntStream.range(0, 4096) .parallel() .mapToObj(i -> generate()) .collect(Collectors.toCollection(() -> new HashSet())); System.out.println(foo); } } > (but I'm not > 100% sure about what kind of synchronization you'll need), or > When executed in parallel, multiple intermediate results may be > instantiated, populated, and merged so as to maintain isolation of > mutable data structures. Therefore, even when executed in parallel > with non-thread-safe data structures (such as |ArrayList|), no > additional synchronization is needed for a parallel reduction. Perhaps it would be interesting to see whether the lambda provided to toCollection is invoked multiple times... import java.util.*; import java.util.concurrent.atomic.*; import java.util.function.*; import java.util.stream.*; public class Slop { private static Object generate() { return new Object(); } private static AtomicInteger counter = new AtomicInteger(); private static class MySet extends HashSet { public MySet() { counter.getAndIncrement(); } } public static void main(String[] args) throws Exception { Collection foo = IntStream.range(0, 4096) .parallel() .mapToObj(i -> generate()) .collect(Collectors.toCollection(() -> new MySet())); System.out.println(foo); System.out.println(counter); } } I got '16'. -- ss at comp dot lancs dot ac dot uk