The idea is the following:
If you try to acquire a shared resource that's already been acquired,
but not yet released then, instead of acquiring it again, you use the value acquired
earlier. You only release the underlying resource when all handles to the shared
resource get released.
More precisely, if y = shared x
and x
is exclusively used here then:
(i) every activation of y
is enclosed into an activation of x
;
(ii) at any time there is at most one activation of x
;
(iii) activations of x
are as short as possible otherwise.
Beware shared
is not referentially transparent in that acquire (shared x)
followed
by acquire (shared x)
will acquire x
twice, so you always want to bind the result
to a variable: let y = shared x in ... (* acquire y multiple times *)
As an example of what you can do with this, in dart
library shared
lets us:
- Coalesce multiple requests for the same entitlement by the same user into one.
- Only establish up to one connection to dart server per user.
In general, it might be helpful when:
- If acquiring the original resource is costly;
- If acquiring
x
multiple times concurrently is not safe;
- If multiple acquirings of
x
would block each other;
- <your idea>.