Skip to content

Instantly share code, notes, and snippets.

@yohhoy
Created December 27, 2014 11:21
Show Gist options
  • Save yohhoy/0699074a5995cb1f71b5 to your computer and use it in GitHub Desktop.
Save yohhoy/0699074a5995cb1f71b5 to your computer and use it in GitHub Desktop.
concurrent reduction
import java.util.stream.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
public class ConcReductTest {
static public void main(String[] args) {
ConcurrentMap<Integer, AtomicInteger> result =
IntStream.range(1, 10_000_001)
.boxed()
.unordered() // invoke concurrent reduction
.parallel()
.collect(Collector.of(
() -> new ConcurrentHashMap<>(),
(m,v) -> {
AtomicInteger a = m.putIfAbsent(v % 10, new AtomicInteger(v));
if (a != null)
a.getAndAdd(v);
},
(m,n) -> { // NOT USED
System.out.println("!");
return null;
},
Collector.Characteristics.CONCURRENT
));
System.out.println("r="+result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment