package interview;

import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;
import java.util.stream.IntStream;

/** Small concurrency answers: atomic counters, virtual threads, odd/even printing with two threads. */
public final class Concurrency {
    private Concurrency() {}

    /** Count with many threads without losing updates. A plain int++ would lose increments. */
    public static long parallelCount(int threads, int incrementsPerThread) throws InterruptedException {
        LongAdder counter = new LongAdder();
        Thread[] ts = new Thread[threads];
        for (int i = 0; i < threads; i++) {
            ts[i] = Thread.ofPlatform().start(() -> {
                for (int j = 0; j < incrementsPerThread; j++) counter.increment();
            });
        }
        for (Thread t : ts) t.join();
        return counter.sum();
    }

    /** Run many blocking tasks on virtual threads (Java 21+). */
    public static List<Integer> squaresOnVirtualThreads(int n) throws InterruptedException, ExecutionException {
        try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) {
            List<Future<Integer>> futures = IntStream.rangeClosed(1, n)
                    .mapToObj(i -> pool.submit(() -> {
                        Thread.sleep(10); // blocking is cheap on a virtual thread
                        return i * i;
                    }))
                    .toList();
            List<Integer> out = new java.util.ArrayList<>();
            for (Future<Integer> f : futures) out.add(f.get());
            return out;
        }
    }

    /** Two threads print 1..max alternately (odd thread, even thread) using wait/notify. */
    public static List<String> oddEven(int max) throws InterruptedException {
        List<String> out = java.util.Collections.synchronizedList(new java.util.ArrayList<>());
        Object lock = new Object();
        AtomicInteger next = new AtomicInteger(1);
        Runnable worker = () -> {
            boolean odd = Thread.currentThread().getName().equals("odd");
            synchronized (lock) {
                while (next.get() <= max) {
                    if ((next.get() % 2 == 1) == odd) {
                        out.add(Thread.currentThread().getName() + ":" + next.getAndIncrement());
                        lock.notifyAll();
                    } else {
                        try { lock.wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
                    }
                }
                lock.notifyAll();
            }
        };
        Thread a = Thread.ofPlatform().name("odd").start(worker);
        Thread b = Thread.ofPlatform().name("even").start(worker);
        a.join();
        b.join();
        return out;
    }
}
