Skip to content

Instantly share code, notes, and snippets.

@vaskoz
Created September 14, 2013 02:03
Show Gist options
  • Save vaskoz/6558231 to your computer and use it in GitHub Desktop.
Save vaskoz/6558231 to your computer and use it in GitHub Desktop.
Count the occurrences of random numbers across threads
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
/**
* Example usage: java RandomizationHistogram 20 21 1
* 20 - threads
* 21 - from 0(inclusive) to 21(exclusive)
* 1 - millisecond delay between thread executions.
*/
public class RandomizationHistogram {
public static void main(String[] args) {
if (args.length != 3) {
System.err.println("Usage: [num threads] [upper range (exclusive)] [delay between thread runs in milliseconds]");
System.exit(1);
}
final int numThreads = Integer.valueOf(args[0]);
final int range = Integer.valueOf(args[1]);
final long delayBetween = Long.valueOf(args[2]);
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(numThreads);
final ConcurrentMap<Integer, AtomicLong> data = new ConcurrentHashMap<>();
List<Runnable> tasks = new ArrayList<>(numThreads);
for (int i = 0; i < numThreads; i++) {
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
ThreadLocalRandom random = ThreadLocalRandom.current();
int value = random.nextInt(0, range);
data.putIfAbsent(value, new AtomicLong(0L));
AtomicLong atomicLong = data.get(value);
atomicLong.getAndIncrement();
}
}, 0L, delayBetween, TimeUnit.MILLISECONDS);
}
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
List<Map.Entry<Integer, AtomicLong>> results = new ArrayList<>(data.entrySet());
Collections.sort(results, new Comparator<Map.Entry<Integer, AtomicLong>>() {
@Override
public int compare(Map.Entry<Integer, AtomicLong> o1, Map.Entry<Integer, AtomicLong> o2) {
return o1.getKey().compareTo(o2.getKey());
}
});
for (Map.Entry<Integer, AtomicLong> entry : results) {
System.out.println("key: " + entry.getKey() + " and value: " + entry.getValue());
}
}
}));
System.out.println("Enter ctrl-C to terminate and display results");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment