Stream reuse in superclass

Brian Goetz brian.goetz at oracle.com
Fri Apr 5 07:51:16 PDT 2013


> I checked your suggestion
>
>                    singleAdd(R row)
>
> and it works fine.

OO to the rescue :)

> But on the other hand I can't understad your other
> comment:
>
>>> Actually this (peek ) won't do anything -- peek is not a terminal
> operation.

Oh, I see what you're doing now -- you're wrapping rows, which gets 
evaluated later.

What I was saying was that:

    stream.peek(...)

is a no-op because streams only do work when they hit a terminal 
operation.  Which the above does not do.

> I guess peek() is evaluted when the stream reaches the superclass and enters
> the forEach.
> I tested with peek() and everithing works as expected, the table had been
> registered to the incomming rows.
> To recheck, I placed a  breakpoint on the addReceiver() method and the
> debugger stops there.
>
> Is there anything bad in using peek() in cases like this?

Absolutely!  What if someone executes this stream in parallel?  Then the 
side effects will happen in whatever thread happens to be processing 
that element.  Are you entirely sure that all the data structures this 
side-effect touches are thread-safe?  For now and for all times?

At this point, you might be tempted to say "but I'm not going to do that 
in parallel, so it's a non-issue."  But, now you've put a time-bomb in 
your code.  At the time you wrote it, you assumed you would never do 
this in parallel.  But does the code capture that assumption?  Are you 
absolutely sure that, five years from now when you have a different job, 
someone else will not be tempted to put .parallel() somewhere?

Side-effects like this are time bombs.  And, there's no reason for it. 
There's almost always a better way.

So, yes, it's bad.  This should never be your first, second, or even 
tenth resort.  Even the name of the method suggests it is not for "do an 
arbitrary side effect now."  Given that you can easily accomplish your 
goal safely (and better) by using the language and library the way it 
was meant to be used, there's no reason to plant time bombs in your code.


More information about the lambda-dev mailing list