001// Copyright (c) FIRST and other WPILib contributors. 002// Open Source Software; you can modify and/or share it under the terms of 003// the WPILib BSD license file in the root directory of this project. 004 005package org.wpilib.math.autodiff; 006 007import java.util.ArrayDeque; 008import java.util.Deque; 009import org.wpilib.util.ErrorMessages; 010import org.wpilib.util.cleanup.CleanupPool; 011 012/** 013 * Cleans up implicitly allocated Variables via try-with-resources. 014 * 015 * <p>This implements a stack of Variable pools containing a default global pool. The user can 016 * create additional pools via try-with-resources. Variable and VariableMatrix instances will 017 * register themselves with the latest pool. 018 * 019 * <p>It's strongly recommended to only instantiate this class via try-with-resources so the close() 020 * methods are always called in the correct order (i.e., nested scopes). 021 */ 022public class VariablePool implements AutoCloseable { 023 private static Deque<VariablePool> s_variablePoolStack = new ArrayDeque<VariablePool>(); 024 025 // Default global pool 026 @SuppressWarnings("PMD.UnusedPrivateField") 027 private static VariablePool s_globalPool = new VariablePool(); 028 029 // Cleans up Variables in the scope of this VariablePool 030 private final CleanupPool m_cleanupPool = new CleanupPool(); 031 032 /** Default constructor. */ 033 @SuppressWarnings("this-escape") 034 public VariablePool() { 035 s_variablePoolStack.addFirst(this); 036 } 037 038 @Override 039 public void close() { 040 m_cleanupPool.close(); 041 s_variablePoolStack.removeFirst(); 042 } 043 044 /** 045 * Registers a Variable in the Variable stack for cleanup. 046 * 047 * @param variable The Variable to register 048 * @return The registered Variable 049 */ 050 public static Variable register(Variable variable) { 051 ErrorMessages.requireNonNullParam(variable, "variable", "register"); 052 s_variablePoolStack.getFirst().m_cleanupPool.register(variable); 053 return variable; 054 } 055}