OLD | NEW |
1 The pool package exposes a `Pool` class which makes it easy to manage a limited | 1 The pool package exposes a `Pool` class which makes it easy to manage a limited |
2 pool of resources. | 2 pool of resources. |
3 | 3 |
4 The easiest way to use a pool is by calling `withResource`. This runs a callback | 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 | 5 and returns its result, but only once there aren't too many other callbacks |
6 currently running. | 6 currently running. |
7 | 7 |
8 ```dart | 8 ```dart |
9 // Create a Pool that will only allocate 10 resources at once. After 30 seconds | 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. | 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)); | 11 final pool = new Pool(10, timeout: new Duration(seconds: 30)); |
12 | 12 |
13 Future<String> readFile(String path) { | 13 Future<String> readFile(String path) { |
14 // Since the call to [File.readAsString] is within [withResource], no more | 14 // Since the call to [File.readAsString] is within [withResource], no more |
15 // than ten files will be open at once. | 15 // than ten files will be open at once. |
16 return pool.withResource(() => return new File(path).readAsString()); | 16 return pool.withResource(() => new File(path).readAsString()); |
17 } | 17 } |
18 ``` | 18 ``` |
19 | 19 |
20 For more fine-grained control, the user can also explicitly request generic | 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 | 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 | 22 what `withResource` does under the covers: requests a resource, then releases it |
23 once the callback completes. | 23 once the callback completes. |
24 | 24 |
25 `Pool` ensures that only a limited number of resources are allocated at once. | 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 | 26 It's the caller's responsibility to ensure that the corresponding physical |
(...skipping 17 matching lines...) Expand all Loading... |
44 // ... | 44 // ... |
45 | 45 |
46 Future<RandomAccessFile> close() { | 46 Future<RandomAccessFile> close() { |
47 return _file.close.then((_) { | 47 return _file.close.then((_) { |
48 _resource.release(); | 48 _resource.release(); |
49 return this; | 49 return this; |
50 }); | 50 }); |
51 } | 51 } |
52 } | 52 } |
53 ``` | 53 ``` |
OLD | NEW |