Class BudgetAllocation

java.lang.Object
com.tnsai.coordination.resources.BudgetAllocation

public class BudgetAllocation extends Object
Tracks resource budgets (tokens, API calls, time) for a group.

BudgetAllocation provides a thread-safe mechanism to allocate and consume named resource budgets. Each budget has an allocated amount, consumed amount, and unit. Consumption is rejected once a budget is exhausted.

Usage Example


 BudgetAllocation budget = new BudgetAllocation();

 // Allocate budgets
 budget.allocate("tokens", 10000, "tokens");
 budget.allocate("api-calls", 100, "calls");

 // Consume
 boolean ok = budget.consume("tokens", 500);  // true, 500/10000
 boolean nope = budget.consume("tokens", 20000); // false, would exceed

 // Check remaining
 Budget b = budget.getBudget("tokens").orElseThrow();
 System.out.println("Remaining: " + b.remaining());
 
  • Constructor Details

    • BudgetAllocation

      public BudgetAllocation()
      Creates a new BudgetAllocation with no budgets.
  • Method Details

    • allocate

      public void allocate(String name, double amount, String unit)
      Allocates a named budget. If a budget with the same name already exists, it is replaced.
      Parameters:
      name - the budget name
      amount - the amount to allocate
      unit - the unit of measurement
      Throws:
      NullPointerException - if name or unit is null
      IllegalArgumentException - if amount is negative
    • consume

      public boolean consume(String name, double amount)
      Consumes an amount from a named budget.

      Returns false (and does not consume) if the budget would be exceeded or the budget does not exist.

      Parameters:
      name - the budget name
      amount - the amount to consume
      Returns:
      true if consumption was successful, false if budget exhausted or not found
      Throws:
      NullPointerException - if name is null
      IllegalArgumentException - if amount is negative
    • getBudget

      public Optional<BudgetAllocation.Budget> getBudget(String name)
      Retrieves a budget by name.
      Parameters:
      name - the budget name
      Returns:
      the budget, or empty if not found
      Throws:
      NullPointerException - if name is null
    • getAllBudgets

      public Map<String,BudgetAllocation.Budget> getAllBudgets()
      Returns all budgets.
      Returns:
      unmodifiable map of budget name to budget
    • reset

      public void reset(String name)
      Resets a specific budget's consumed amount to zero.
      Parameters:
      name - the budget name to reset
      Throws:
      NullPointerException - if name is null
    • resetAll

      public void resetAll()
      Resets all budgets' consumed amounts to zero.