package dev.elaine.concurrency;

import java.util.concurrent.CountDownLatch;

public final class FalseSharingSample {
    private static final int ITERATIONS = 20_000_000;

    private FalseSharingSample() {
    }

    static final class Counters {
        volatile long left;
        volatile long right;
    }

    public static void main(String[] args) throws InterruptedException {
        Counters counters = new Counters();
        CountDownLatch start = new CountDownLatch(1);
        Thread leftWorker = Thread.ofPlatform().start(() -> incrementLeft(counters, start));
        Thread rightWorker = Thread.ofPlatform().start(() -> incrementRight(counters, start));

        long started = System.nanoTime();
        start.countDown();
        leftWorker.join();
        rightWorker.join();
        long elapsedMillis = (System.nanoTime() - started) / 1_000_000;

        System.out.printf("left=%d, right=%d, elapsed=%d ms%n",
                counters.left, counters.right, elapsedMillis);
    }

    private static void incrementLeft(Counters counters, CountDownLatch start) {
        await(start);
        for (int index = 0; index < ITERATIONS; index++) {
            counters.left++;
        }
    }

    private static void incrementRight(Counters counters, CountDownLatch start) {
        await(start);
        for (int index = 0; index < ITERATIONS; index++) {
            counters.right++;
        }
    }

    private static void await(CountDownLatch latch) {
        try {
            latch.await();
        } catch (InterruptedException exception) {
            Thread.currentThread().interrupt();
            throw new IllegalStateException("实验被中断", exception);
        }
    }
}
