Design a reusable inventory that supports concurrent purchases and restocking without overselling or losing updates.
Implement the ThreadSafeInventory class:
ThreadSafeInventory(initialStock) initializes the available stock.tryPurchase(quantity, onPurchased) purchases exactly quantity units if enough stock is available.restock(quantity) adds exactly quantity units.available() returns the current stock from a thread-safe snapshot.tryPurchase must atomically check whether stock >= quantity and, if so, subtract quantity. Return true for a successful purchase and false when there is insufficient stock.
Invoke onPurchased exactly once for a successful purchase and never for a rejected purchase. The stock must already be decremented when the callback begins. Run the callback without holding the inventory lock so other purchases, restocks, and reads can progress while it executes. The method returns only after its own callback finishes.
All successful purchases, restocks, and reads on one instance must be linearizable. The stock must never become negative, and no restocked units may be lost. Different inventory instances must be independent.
The judge supplies all callbacks. They return normally and do not call the same inventory. Standard concurrency, callback, collection, lock, and thread APIs are preloaded, so you do not need import, include, package, or using statements.
Input:
Output:
Explanation: The rejected purchase does not change the stock and does not invoke its callback.
Input:
Output:
Explanation: Checking and subtracting must be one critical section. If both threads checked first and subtracted later, they could oversell the inventory.
0 <= initialStock <= 10^91 <= quantity <= 10^910000 operations are performed on one instance.Input
initialStock = 10 operations = [ tryPurchase(3), available(), tryPurchase(8), restock(5), available() ]
Output
[true, 7, false, 12]
Run is a quick check against the first couple of scenarios, which is roughly what these examples describe. Submit puts your class under the full set, which stays hidden.

