Questions about Stream/Iterable/Files - and possibly the compiler

Paul Sandoz paul.sandoz at oracle.com
Fri Nov 6 23:03:15 UTC 2015


> On 6 Nov 2015, at 19:58, Fabrizio Giudici <fabrizio.giudici at tidalwave.it> wrote:
> 
> On Fri, 06 Nov 2015 14:39:29 +0100, Paul Sandoz <paul.sandoz at oracle.com> wrote:
> 
>> 
>>> On 6 Nov 2015, at 14:19, Fabrizio Giudici <fabrizio.giudici at tidalwave.it> wrote:
>>> 
>>> 
>>>> I logged an issue:
>>>> 
>>>> https://bugs.openjdk.java.net/browse/JDK-8141608 <https://bugs.openjdk.java.net/browse/JDK-8141608>
>>> 
>>> Thanks to Remi and Paul for the complete explanation. Concerning JDK-8141608, I lile Peter Levart's comment about making a specific Collector.
>> 
>> There is a problem with that approach. At the moment the Collector does not get to control whether the stream is executed in parallel or sequentially.
> 
> Sure, I understand. I think it would be ok if the Collector has as a pre-requisite that it can't be used with a parallel Stream.

That might be fine for your needs, but i think not appropriate for the JDK.


> I assume that if the stream is not parallel, the runtime won't ever try to execute the Collector in parallel... right?

Correct.


> That's what I see from the tests I've executed so far.
> 
> I've tried to write such a FileCollector, with a check that throws an exception if the accumulator Supplier function is called more than once, with code such as:
> 
>    private final AtomicBoolean parallelChecker = new AtomicBoolean();
> 
>    @Override
>    public Supplier<PrintWriter> supplier()
>      {
>        return this::oneShotPrintWriterSupplier;
>      }
> 
>    private PrintWriter oneShotPrintWriterSupplier()
>      {
>        if (parallelChecker.getAndSet(true))
>          {
>            fail();
>          }
> 
>        return pw;
>      }
> 
> It seems to properly detect when it's called with a parallel Stream. Do you think that it's safe enough?

It might depend on what you consider unsafe. Some elements may be accumulated before the exception is produced. There is no guarantee that the supplier will be operated on the appropriate number of times before accumulation starts.

Paul.



More information about the core-libs-dev mailing list