Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.util.concurrent.*;
- public class Main {
- private static final int MAX_THREADS = 4;
- private static byte[] data = new byte[500 * 1024 * 1024];
- private static ExecutorService executor = Executors.newCachedThreadPool();
- public static void main(String[] args) throws InterruptedException, ExecutionException {
- for (int k = 0; k < 50; k++) {
- int numberOfThreads = k % MAX_THREADS + 1;
- long start = System.currentTimeMillis();
- runBenchmark(numberOfThreads);
- long end = System.currentTimeMillis();
- checkDataIsConsistent();
- printResults(numberOfThreads, start, end);
- }
- executor.shutdown();
- }
- private static void runBenchmark(int numberOfThreads) throws InterruptedException, ExecutionException {
- List<Future<?>> futures = new ArrayList<Future<?>>();
- for (int i = 0; i < numberOfThreads; i++) {
- futures.add(executor.submit(new Worker(i, numberOfThreads)));
- }
- for (Future<?> future : futures) {
- future.get();
- }
- }
- private static void checkDataIsConsistent() {
- int reference = data[0];
- for (int i = 0; i < data.length; i++) {
- int current = data[i];
- if (current != reference) {
- throw new AssertionError("inconsistent data at index " + i + ": " + current + " != " + reference);
- }
- }
- }
- private static void printResults(int numberOfThreads, long start, long end) {
- if (numberOfThreads == 1) {
- System.out.println();
- }
- System.out.println(numberOfThreads + " Thread(s): " + (end - start) + " ms");
- }
- private static class Worker implements Runnable {
- private final int workerId;
- private final int totalWorkers;
- public Worker(int workerId, int totalWorkers) {
- this.workerId = workerId;
- this.totalWorkers = totalWorkers;
- }
- @Override
- public void run() {
- int chunkSize = data.length / totalWorkers;
- int start = chunkSize * workerId;
- int end;
- if (workerId == totalWorkers - 1) {
- end = data.length;
- } else {
- end = start + chunkSize;
- }
- for (int i = start; i < end; i++) {
- doSomeComputation(i);
- }
- }
- private void doSomeComputation(int i) {
- data[i] = (byte) Math.sqrt(data[i] + 42);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement