commit | 005271ccb91a66a93c0fa5df59802c035ca5f4c0 | [log] [tgz] |
---|---|---|
author | Franklin Yow <58489007+franklinyow@users.noreply.github.com> | Thu Apr 01 12:51:29 2021 -0700 |
committer | GitHub <noreply@github.com> | Thu Apr 01 12:51:29 2021 -0700 |
tree | 693b859bbce410967e7390bcfe999cfc390dce80 | |
parent | 878759ad4aedd019cf5e86a1b5699140557b11fd [diff] | |
parent | b2dbf2969f466b688e664c884138ac884b88d0db [diff] |
Merge pull request #54 from dart-lang/franklinyow-patch-1 Update LICENSE
The pool package exposes a Pool
class which makes it easy to manage a limited pool of resources.
The easiest way to use a pool is by calling withResource
. This runs a callback and returns its result, but only once there aren't too many other callbacks currently running.
// Create a Pool that will only allocate 10 resources at once. After 30 seconds // of inactivity with all resources checked out, the pool will throw an error. final pool = new Pool(10, timeout: new Duration(seconds: 30)); Future<String> readFile(String path) { // Since the call to [File.readAsString] is within [withResource], no more // than ten files will be open at once. return pool.withResource(() => new File(path).readAsString()); }
For more fine-grained control, the user can also explicitly request generic PoolResource
objects that can later be released back into the pool. This is what withResource
does under the covers: requests a resource, then releases it once the callback completes.
Pool
ensures that only a limited number of resources are allocated at once. It‘s the caller’s responsibility to ensure that the corresponding physical resource is only consumed when a PoolResource
is allocated.
class PooledFile implements RandomAccessFile { final RandomAccessFile _file; final PoolResource _resource; static Future<PooledFile> open(String path) { return pool.request().then((resource) { return new File(path).open().then((file) { return new PooledFile._(file, resource); }); }); } PooledFile(this._file, this._resource); // ... Future<RandomAccessFile> close() { return _file.close.then((_) { _resource.release(); return this; }); } }