commit | 9bf6a8ec011fb52fa259109760f649567d514813 | [log] [tgz] |
---|---|---|
author | nweiz@google.com <nweiz@google.com> | Fri Jul 25 00:32:40 2014 +0000 |
committer | nweiz@google.com <nweiz@google.com> | Fri Jul 25 00:32:40 2014 +0000 |
tree | df2493b0cfdb72166850ffc1cdb075fd4773ab2e | |
parent | f94ba8e392e66c2fc04d5e14b36c80211a42986e [diff] |
Revert r38549, r38552, and r38557. It's currently too difficult to include a third party package for it to be worthwhile for this use case. R=alanknight@google.com Review URL: https://codereview.chromium.org//419683002 git-svn-id: https://dart.googlecode.com/svn/branches/bleeding_edge/dart/pkg/pool@38564 260f80e4-7a28-3924-810f-c04153c831b5
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(() => return 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; }); } }