Connection Pool (Rust)
Topics: concurrency, resource pooling
Problem
Implement a fixed-size pool of reusable connections (any C: Closer):
pub trait Closer { fn close(&self); }
pub enum PoolError { Closed, Timeout }
impl<C: Closer> Pool<C> {
pub fn new<F: FnMut() -> Result<C, String>>(size: usize, dial: F) -> Result<Self, String>;
pub fn acquire(&self) -> Result<C, PoolError>;
pub fn acquire_timeout(&self, timeout: Duration) -> Result<C, PoolError>;
pub fn release(&self, conn: C);
pub fn close(&self);
}
new pre-warms size connections by calling dial eagerly.
acquire blocks until a connection is free; acquire_timeout gives up with Timeout.
After close, both return Closed.
release returns a connection to the pool — but if the pool is already full (an overflow) or
closed, it close()s that connection instead.
close closes every idle connection and is idempotent (calling it twice must not panic).
The Go version uses context for Acquire; this port splits that into acquire (block) and
acquire_timeout(Duration). Pool is Clone (cheap Arc handle) so it can be shared across
threads.
Hint: Mutex<Vec<C>> + Condvar — acquire waits on the condvar, release pushes and notifies.
Grading
Your solution.rs is compiled together with a trusted tests.rs (which include!s it) using
rustc --test. Only solution.rs is yours to edit.
Sign in to submit your solution.