// The limit overrun, on one gift card, in Java. Four versions of the same request,
// each released on thirty threads at once; the page limit_overrun.html shows the
// parts between "---- snippet" and "---- end" and the lines each run prints.
//   java Overrun race    read the balance, check it, confirm the order, decrement
//   java Overrun lock    the same under the card's lock
//   java Overrun cas     the same with a compare-and-set loop, no lock
//   java Overrun queue   the same with one owner: requests queued, served in turn
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

public class Overrun {
  static final int THREADS = 30, AMOUNT = 10;

  // The shop keeps the balance in a database. Between reading it and writing it back,
  // the order is confirmed: a round trip or two to other services, about a millisecond.
  static void confirmOrder() {
    try { Thread.sleep(1); } catch (InterruptedException e) { }
  }

  // Each database statement is atomic on its own: the read, and the decrement. The two are not one.
  static final class Racy {
    // ---- snippet
    static int balance = 10;                  // the card, in the shop's database
    static final Object card = new Object();

    static boolean redeem(int x) {
      int b;
      synchronized (card) { b = balance; }    // SELECT balance             (one statement)
      if (b < x) return false;                // the check
      confirmOrder();                         // the order is built: about a millisecond
      synchronized (card) { balance -= x; }   // UPDATE balance = balance - x (one statement)
      return true;
    }
    // ---- end
  }

  // Forbid the interleaving: the read, the check and the decrement under one lock.
  static final class Locked {
    static int balance = 10;
    static final Object card = new Object();

    // ---- snippet
    static boolean redeem(int x) {
      synchronized (card) {                   // read to write: nothing of ours between
        if (balance < x) return false;
        confirmOrder();
        balance -= x;
        return true;
      }
    }
    // ---- end
  }

  // Detect the interleaving and redo: write only if the balance is still the one read;
  // the order is confirmed after the debit has taken effect, so a failed attempt has nothing to undo.
  static final class Cas {
    // ---- snippet
    static final AtomicInteger balance = new AtomicInteger(10);

    static boolean redeem(int x) {
      while (true) {
        int b = balance.get();                        // read
        if (b < x) return false;                      // check
        if (balance.compareAndSet(b, b - x)) break;   // still b? then b - x, in one step
        // another request wrote first: read again
      }
      confirmOrder();                                 // after the debit: nothing to undo
      return true;
    }
    // ---- end
  }

  // Make the order irrelevant: one thread owns the balance; the others send it requests.
  static final class Owner {
    record Request(int amount, CountDownLatch done, boolean[] slot) {
      Request(int amount) { this(amount, new CountDownLatch(1), new boolean[1]); }
      void answer(boolean ok) { slot[0] = ok; done.countDown(); }
      boolean reply() throws InterruptedException { done.await(); return slot[0]; }
    }
    static final BlockingQueue<Request> inbox = new ArrayBlockingQueue<>(THREADS);
    static volatile int left;                 // the balance, reported when the owner is stopped

    // ---- snippet
    static Thread owner = new Thread(() -> {
      int b = 10;                             // the balance: a local variable of one thread
      try {
        while (true) {
          Request r = inbox.take();           // the next request, in the order of arrival
          boolean ok = b >= r.amount();
          if (ok) { confirmOrder(); b -= r.amount(); }
          r.answer(ok);
        }
      } catch (InterruptedException e) { left = b; }
    });
    // ---- end

    static boolean redeem(int x) throws InterruptedException {
      Request r = new Request(x);
      inbox.put(r);
      return r.reply();
    }
  }

  public static void main(String[] args) throws Exception {
    String mode = args.length > 0 ? args[0] : "race";
    if (mode.equals("queue")) Owner.owner.start();
    CountDownLatch go = new CountDownLatch(1);
    AtomicInteger accepted = new AtomicInteger();
    Thread[] ts = new Thread[THREADS];
    for (int i = 0; i < THREADS; i++) {
      ts[i] = new Thread(() -> {
        try {
          go.await();
          boolean ok = switch (mode) {
            case "lock"  -> Locked.redeem(AMOUNT);
            case "cas"   -> Cas.redeem(AMOUNT);
            case "queue" -> Owner.redeem(AMOUNT);
            default      -> Racy.redeem(AMOUNT);
          };
          if (ok) accepted.incrementAndGet();
        } catch (InterruptedException e) { return; }
      });
      ts[i].start();
    }
    go.countDown();                           // all thirty requests released at once
    for (Thread t : ts) t.join();
    int left = switch (mode) {
      case "lock"  -> Locked.balance;
      case "cas"   -> Cas.balance.get();
      case "queue" -> { Owner.owner.interrupt(); Owner.owner.join(); yield Owner.left; }
      default      -> Racy.balance;
    };
    System.out.println(mode + ": card worth " + AMOUNT + ", " + THREADS + " requests of " + AMOUNT
        + ": accepted " + accepted.get() + ", balance left " + left);
  }
}
