0

So let's say we have the following setup:

List<String> strings = Arrays.asList( "lore ipsum ..", ... 10000 strings);
AtomicInteger count = new AtomicInteger(0);
strings.parallelStream().forEach( myString -> {
   System.out.println(count.incrementAndGet());
   System.out.println(myString); 
   // ... do more computing
});

Will this code perform considerable faster if I don't use the atomic variable? Is it a good practice to use atomic variables or better try to avoid them if you can?

Other links: Parallel stream - race conditions with atomic variables, Parallel processing

Edwin
  • 2,146
  • 20
  • 26
  • The "not so important" part of the example is really bad in this case, the main time consuming operation will be `System.out.println` and `incrementAndGet` will be like nothing compared to that. If "your work" part actually takes some time, then I wouldn't really worry about `AtomicInteger`. – Amongalen Jan 14 '21 at 15:51
  • i dont think it will impact performance , as atomicinteger is non blocking. with the context of thread contention – JustTry Jan 14 '21 at 15:57
  • Why not `parallelStream().count()`? Why count manually? i don't have the answer, but [`LongAdder`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/LongAdder.html) is a class to reduce contention when incrementing a long value (i.e. counting) – knittl Jan 14 '21 at 15:57
  • @knittl because the main goal is not counting, that's just for debugging. – Edwin Jan 14 '21 at 16:00
  • @Amongalen the `Sysout` is just for this example in the actual code will be a logger and the function will do something else. – Edwin Jan 14 '21 at 16:01

0 Answers0