Module Lwt_pool
External resource pools.
This module provides an abstraction for managing collections of resources. One example use case is for managing a pool of database connections, where instead of establishing a new connection each time you need one (which is expensive), you can keep a pool of opened connections and reuse ones that are free.
It also provides the capability of:
- specifying the maximum number of resources that the pool can manage simultaneously,
- checking whether a resource is still valid before/after use, and
- performing cleanup logic before dropping a resource.
The following example illustrates how it is used with an imaginary Db module:
let uri = "postgresql://localhost:5432"
(* Create a database connection pool with max size of 10. *)
let pool =
Lwt_pool.create 10
~dispose:(fun connection -> Db.close connection |> Lwt.return)
(fun () -> Db.connect uri |> Lwt.return)
(* Use the pool in queries. *)
let create_user name =
Lwt_pool.use pool (fun connection ->
connection
|> Db.insert "users" [("name", name)]
|> Lwt.return
)Note that this is not intended to keep a pool of system threads. If you want to have such pool, consider using Lwt_preemptive.
val create : int -> ?validate:('a -> bool Lwt.t) -> ?check:('a -> (bool -> unit) -> unit) -> ?dispose:('a -> unit Lwt.t) -> (unit -> 'a Lwt.t) -> 'a tcreate n ?check ?validate ?dispose fcreates a new pool with at mostnelements.fis used to create a new pool element. Elements are created on demand and re-used until disposed of.- parameter validate
is called each time a pool element is accessed by
use, before the element is provided touse's callback. Ifvalidate elementresolves totruethe element is considered valid and is passed to the callback for use as-is. Ifvalidate elementresolves tofalsethe tested pool element is passed todisposethen dropped, with a new one is created to takeelement's place in the pool.validateis available since Lwt 3.2.0.
- parameter check
is called after the resolution of
use's callback when the resolution is a failed promise.check element is_okmust callis_okexactly once withtrueifelementis still valid andfalseotherwise. Ifcheckcallsis_ok falsethendisposewill be run onelementand the element will not be returned to the pool.
val use : 'a t -> ('a -> 'b Lwt.t) -> 'b Lwt.tuse p frequests one free element of the poolpand gives it to the functionf. The element is put back into the pool after the promise created byfcompletes.In the case that
pis exhausted and the maximum number of elements is reached,usewill wait until one becomes free.
val clear : 'a t -> unit Lwt.tclear pwill clear all elements inp, calling thedisposefunction associated withpon each of the cleared elements. Any elements frompwhich are currently in use will be disposed of once they are released.The next call to
use pafterclear pguarantees a freshly created pool element.Disposals are performed sequentially in an undefined order.
- since
- 3.2.0