Skip to main content

Pool

Struct Pool 

Source
pub struct Pool<M: Manager>(/* private fields */);
Available on crate feature std only.
Expand description

A thread-safe pool of reusable resources.

A Pool<M> lends out resources built by a Manager, reclaiming and recycling each one when its Pooled guard is dropped. It is cheap to clone — every clone is a handle onto the same shared pool — so share it across threads by cloning rather than wrapping it in another Arc.

The pool is runtime-agnostic and carries no async dependency. get blocks the calling thread until a resource is available; in an async context, acquire on a blocking-friendly executor thread (for example tokio::task::spawn_blocking). The returned guard is Send, so it can be held across .await points.

§Examples

use pool_mod::{Manager, Pool};
use std::convert::Infallible;

struct Connections;
impl Manager for Connections {
    type Resource = String;
    type Error = Infallible;
    fn create(&self) -> Result<String, Infallible> { Ok(String::new()) }
    fn recycle(&self, c: &mut String) -> Result<(), Infallible> { c.clear(); Ok(()) }
}

let pool = Pool::builder(Connections).max_size(4).build()
    .expect("configuration is valid");

let mut conn = pool.get().expect("a connection is available");
conn.push_str("SELECT 1");
assert_eq!(pool.status().in_use, 1);
drop(conn);
assert_eq!(pool.status().in_use, 0);

Implementations§

Source§

impl<M: Manager> Pool<M>

Source

pub fn builder(manager: M) -> Builder<M>

Start building a pool for manager with the default configuration.

§Examples
use pool_mod::{Manager, Pool};
use std::convert::Infallible;
let pool = Pool::builder(M).max_size(8).min_idle(2).build()
    .expect("configuration is valid");
assert_eq!(pool.status().max_size, 8);
Source

pub fn new(manager: M) -> Result<Self, Error<M::Error>>

Build a pool for manager with the default configuration.

A shortcut for Pool::builder(manager).build().

§Errors

Returns Error::Backend if pre-creating the initial resources fails. (With the default min_idle of 0, no resources are created up front, so the default-configured pool only fails to build if you have customized the configuration through Pool::builder instead.)

§Examples
use pool_mod::{Manager, Pool};
use std::convert::Infallible;
let pool = Pool::new(M).expect("configuration is valid");
assert_eq!(pool.status().max_size, 10); // the default
Source

pub fn get(&self) -> Result<Pooled<M>, Error<M::Error>>

Borrow a resource, waiting up to the configured create_timeout if the pool is saturated.

Reuses an idle resource when one is available (after validation), grows the pool toward max_size when it is not, and otherwise blocks until a resource is returned or the timeout elapses.

§Errors
§Examples
use pool_mod::{Manager, Pool};
use std::convert::Infallible;
let pool = Pool::builder(M).max_size(2).build().expect("valid");
let resource = pool.get().expect("available");
assert_eq!(*resource, 7);
Source

pub fn get_timeout( &self, timeout: Duration, ) -> Result<Pooled<M>, Error<M::Error>>

Borrow a resource, waiting at most timeout regardless of the configured create_timeout.

A timeout of Duration::ZERO makes this a non-blocking try: it returns Error::Timeout at once if no resource can be handed out immediately.

§Errors
§Examples
use std::time::Duration;
use pool_mod::{Error, Manager, Pool};
use std::convert::Infallible;
let pool = Pool::builder(M).max_size(1).build().expect("valid");
let held = pool.get().expect("first checkout");
// The single slot is taken, so an immediate retry times out.
assert!(matches!(pool.get_timeout(Duration::ZERO), Err(Error::Timeout)));
Source

pub fn try_get(&self) -> Result<Pooled<M>, Error<M::Error>>

Borrow a resource without ever blocking.

Returns a resource if one can be handed out immediately — an idle resource is ready, or the pool has room to create one — and otherwise returns Error::Timeout at once. Equivalent to get_timeout(Duration::ZERO).

§Errors
§Examples
use pool_mod::{Error, Manager, Pool};
use std::convert::Infallible;
let pool = Pool::builder(M).max_size(1).build().expect("valid");
let first = pool.try_get().expect("room to create one");
// The only slot is taken, so the next try fails immediately.
assert!(matches!(pool.try_get(), Err(Error::Timeout)));
Source

pub fn status(&self) -> Status

Take a snapshot of the pool’s current occupancy.

§Examples
use pool_mod::{Manager, Pool};
use std::convert::Infallible;
let pool = Pool::builder(M).max_size(4).min_idle(1).build().expect("valid");
let status = pool.status();
assert_eq!(status.idle, 1);
assert_eq!(status.max_size, 4);
Source

pub fn close(&self)

Close the pool: discard every idle resource and reject all future checkouts with Error::Closed.

Resources currently checked out are unaffected and are simply dropped (not returned to the idle set) when their guards fall. Closing is idempotent. Idle resources are dropped outside the pool’s lock, so a slow resource destructor does not block other threads.

§Examples
use pool_mod::{Error, Manager, Pool};
use std::convert::Infallible;
let pool = Pool::builder(M).max_size(2).min_idle(2).build().expect("valid");
pool.close();
assert!(pool.is_closed());
assert!(matches!(pool.get(), Err(Error::Closed)));
Source

pub fn is_closed(&self) -> bool

Report whether the pool has been closed.

Trait Implementations§

Source§

impl<M: Manager> Clone for Pool<M>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

§

impl<M> Freeze for Pool<M>

§

impl<M> RefUnwindSafe for Pool<M>
where M: RefUnwindSafe,

§

impl<M> Send for Pool<M>

§

impl<M> Sync for Pool<M>

§

impl<M> Unpin for Pool<M>

§

impl<M> UnsafeUnpin for Pool<M>

§

impl<M> UnwindSafe for Pool<M>
where M: RefUnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.