package dev.banking;

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicDemo {
    private static int normalCounter = 0;
    private static final AtomicInteger atomicCounter = new AtomicInteger(0);

    public static void main(String[] args) throws InterruptedException {
        int threads = 10;
        int increments = 1000;

        Thread[] threadList = new Thread[threads * 2];

        for (int i = 0; i < threads; i++) {
            threadList[i * 2] = new Thread(() -> {
                for (int j = 0; j < increments; j++) {
                    normalCounter++;
                }
            });

            threadList[i * 2 + 1] = new Thread(() -> {
                for (int j = 0; j < increments; j++) {
                    atomicCounter.incrementAndGet();
                }
            });

            threadList[i * 2].start();
            threadList[i * 2 + 1].start();
        }

        for (Thread t : threadList) {
            t.join();
        }
        int expected = threads * increments;
        System.out.println("Expected value: " + expected);
        System.out.println("Normal int:      " + normalCounter);
        System.out.println("AtomicInteger:   " + atomicCounter.get());
    }
}