Skip to content

Instantly share code, notes, and snippets.

@timyates
Last active August 29, 2015 14:00
Show Gist options
  • Save timyates/348066a6a749ad0676f7 to your computer and use it in GitHub Desktop.
Save timyates/348066a6a749ad0676f7 to your computer and use it in GitHub Desktop.
Gaussian distribution in Java 8 with parallel Streams and LongAdder
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.LongAdder;
import java.util.stream.IntStream;
public class LongAdderTest {
ConcurrentHashMap<Integer,LongAdder> frequencyMap = new ConcurrentHashMap<>() ;
Random rnd = new Random() ;
void run() {
IntStream.range( 0, 10000 )
.parallel()
.forEach( ( n ) -> {
Integer key = Double.valueOf( rnd.nextGaussian() + 5 ).intValue() ;
frequencyMap.computeIfAbsent( key, ( k ) -> new LongAdder() ).increment() ;
} ) ;
System.out.println( frequencyMap );
}
public static void main( String[] args ) {
new LongAdderTest().run() ;
}
}
// Requires Java 8 and Groovy 2.3
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.LongAdder
import static groovyx.gpars.GParsPool.withPool
new Random().with { rnd ->
new ConcurrentHashMap<Integer,LongAdder>().with { frequencyMap ->
withPool {
(0..10000).eachParallel { n ->
Integer key = rnd.nextGaussian() + 5
frequencyMap.computeIfAbsent( key, { k -> new LongAdder() } ).increment()
}
}
println frequencyMap
}
}
// Requires Java 8 and Groovy 2.3
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.LongAdder
import java.util.stream.IntStream;
new Random().with { rnd ->
new ConcurrentHashMap<Integer,LongAdder>().with { frequencyMap ->
IntStream.range( 0, 10000 )
.parallel()
.forEach { n ->
Integer key = rnd.nextGaussian() + 5
frequencyMap.computeIfAbsent( key, { k -> new LongAdder() } ).increment()
}
println frequencyMap
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment