OLD | NEW |
(Empty) | |
| 1 The pool package exposes a `Pool` class which makes it easy to manage a limited |
| 2 pool of resources. |
| 3 |
| 4 The easiest way to use a pool is by calling `withResource`. This runs a callback |
| 5 and returns its result, but only once there aren't too many other callbacks |
| 6 currently running. |
| 7 |
| 8 ```dart |
| 9 // Create a Pool that will only allocate 10 resources at once. After 30 seconds |
| 10 // of inactivity with all resources checked out, the pool will throw an error. |
| 11 final pool = new Pool(10, timeout: new Duration(seconds: 30)); |
| 12 |
| 13 Future<String> readFile(String path) { |
| 14 // Since the call to [File.readAsString] is within [withResource], no more |
| 15 // than ten files will be open at once. |
| 16 return pool.withResource(() => return new File(path).readAsString()); |
| 17 } |
| 18 ``` |
| 19 |
| 20 For more fine-grained control, the user can also explicitly request generic |
| 21 `PoolResource` objects that can later be released back into the pool. This is |
| 22 what `withResource` does under the covers: requests a resource, then releases it |
| 23 once the callback completes. |
| 24 |
| 25 `Pool` ensures that only a limited number of resources are allocated at once. |
| 26 It's the caller's responsibility to ensure that the corresponding physical |
| 27 resource is only consumed when a `PoolResource` is allocated. |
| 28 |
| 29 ```dart |
| 30 class PooledFile implements RandomAccessFile { |
| 31 final RandomAccessFile _file; |
| 32 final PoolResource _resource; |
| 33 |
| 34 static Future<PooledFile> open(String path) { |
| 35 return pool.request().then((resource) { |
| 36 return new File(path).open().then((file) { |
| 37 return new PooledFile._(file, resource); |
| 38 }); |
| 39 }); |
| 40 } |
| 41 |
| 42 PooledFile(this._file, this._resource); |
| 43 |
| 44 // ... |
| 45 |
| 46 Future<RandomAccessFile> close() { |
| 47 return _file.close.then((_) { |
| 48 _resource.release(); |
| 49 return this; |
| 50 }); |
| 51 } |
| 52 } |
| 53 ``` |
OLD | NEW |