use std::sync::RwLock;
use once_cell::sync::Lazy;
use super::{
Pools,
config::PoolConfig,
thread_local::{get_thread_pools, has_thread_pools, set_thread_pools},
};
static DEFAULT_CONFIG: Lazy<RwLock<PoolConfig>> = Lazy::new(|| RwLock::new(PoolConfig::default()));
pub fn set_default_pool_config(config: PoolConfig) {
*DEFAULT_CONFIG.write().unwrap() = config;
}
pub fn get_default_pool_config() -> PoolConfig {
DEFAULT_CONFIG.read().unwrap().clone()
}
pub fn get_or_init_pools() -> Pools {
get_thread_pools().unwrap_or_else(|| {
let config = DEFAULT_CONFIG.read().unwrap().clone();
let pools = Pools::new(config.max_pool_size);
set_thread_pools(pools.clone());
pools
})
}
pub fn ensure_thread_pools() {
if !has_thread_pools() {
get_or_init_pools();
}
}
pub fn thread_pools_lazy() -> Pools {
get_or_init_pools()
}
#[cfg(test)]
pub mod tests {
use super::*;
use crate::value::column::pool::thread_local::clear_thread_pools;
#[test]
fn test_get_or_init_pools() {
clear_thread_pools();
assert!(!has_thread_pools());
let pools1 = get_or_init_pools();
assert!(has_thread_pools());
let pools2 = get_or_init_pools();
assert!(has_thread_pools());
clear_thread_pools();
}
#[test]
fn test_ensure_thread_pools() {
clear_thread_pools();
assert!(!has_thread_pools());
ensure_thread_pools();
assert!(has_thread_pools());
ensure_thread_pools();
assert!(has_thread_pools());
clear_thread_pools();
}
#[test]
fn test_custom_default_config() {
let custom_config = PoolConfig {
max_pool_size: 64,
enable_statistics: true,
auto_clear_threshold: Some(5000),
prewarm_capacities: vec![32, 128],
};
set_default_pool_config(custom_config.clone());
let retrieved = get_default_pool_config();
assert_eq!(retrieved.max_pool_size, 64);
assert_eq!(retrieved.enable_statistics, true);
assert_eq!(retrieved.auto_clear_threshold, Some(5000));
assert_eq!(retrieved.prewarm_capacities, vec![32, 128]);
set_default_pool_config(PoolConfig::default());
}
#[test]
fn test_thread_pools_lazy() {
clear_thread_pools();
assert!(!has_thread_pools());
let pools = thread_pools_lazy();
assert!(has_thread_pools());
clear_thread_pools();
}
}