Reputation: 5086
Is there any way to monitor the execution resp. collection/reduction of a parallel Stream in Java 8? I would like to know, how many of the elements are already processed.
In sequential programming I could just do the whole task with for-loops and add some counters, which I can print to the stdout every now and then, to see how long it will take. But for parallel streams I don't see any easy and straightforward way to do the same.
Upvotes: 2
Views: 710
Reputation: 95346
You can use the peek()
method to watch the elements go by. If the stream is being processed in parallel, you'll get these calls from all the threads in which elements are being processed.
That said, its probably not a smart idea. First of all, you'll have to contend with thread-safety issues; if you want to maintain some global state of the calculation, you'll have to use some sort of synchronization to keep it consistent, otherwise any statistics collected will be meaningless. And that coordination will kill most of (or more than all of) the benefit that parallelism would have given you, since now you'll have multiple threads contending for a lock all the time, when the point was to let these separate threads run free on disjoint portions of the data. This is an example where your desire to observe a calculation will dramatically change its performance characteristics.
Remember, parallelism is purely an optimization -- the only value of using parallelism is to get to the answer faster. But if you're going to tie the processors shoelaces together like this, you're not going to get that benefit.
Upvotes: 6