Last active
August 29, 2015 14:00
-
-
Save timyates/348066a6a749ad0676f7 to your computer and use it in GitHub Desktop.
Gaussian distribution in Java 8 with parallel Streams and LongAdder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() ; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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