On 4/30/20 8:10 PM, Maurizio Cimadamore wrote:
On 30/04/2020 01:06, Peter Levart wrote:
Think differently: what if the client succeeded in closing the
segment, just because it did it in a time window when no thread in
the thread pool held an open scope (this is entirely possible with
parallel stream for example since threads periodically acquire and
close scopes). This would have the same effect on threads in the
thread pool - they would not be able to continue their work... What
I'm trying to say is that this is just a mechanism to make things
safe, not to coordinate work. If program wants to avoid trouble, it
must carefully coordinate work of threads.
This appear to me to be a bit of a slippery slope? Sure, if somebody
prematurely calls close() on a segment while other threads are
accessing it, it could be seen as undefined behavior (a la C
specifications ;-) ), but then, if you pull on the same string, why
even bother with confinement in the first place? If you call close()
prematurely and you get a VM crash that's on you?
Luckily, I think I have fixed this shortcoming in the alternative
MemoryScope:
http://cr.openjdk.java.net/~plevart/jdk-dev/8243491_MemoryScope/v2/MemoryScope.java
The trick is in using a 'state' with 3 values: OPEN, CLOSING, CLOSED ...
The acquiring thread does the following in order:
- increments the 'acquires' scalable counter (volatile write)
- reads the 'state' (volatile read) and then enters a spin-loop:
- if state == STATE_OPEN the acquire succeeded (this is fast path);
else
- if state == STATE_CLOSING it spin-loops re-reading 'state' in
each iteration; else
- if state == STATE_CLOSED it increments 'releases' scalable
counter and throws exception
The closing thread does the following in order:
- writes STATE_CLOSING to 'state' (volatile write)
- sums the 'releases' scalable counter (volatile reads)
- sums the 'acquires' scalable counter (volatile reads)
- compares both sums and:
- if they don't match then it writes back STATE_OPEN to 'state'
(volatile write) and throws exception; else
- it writes STATE_CLOSED to 'state' (volatile write) and executes
cleanup action
This, I think, is better, isn't it?
Regards, Peter
Maurizio