Repository navigation
Harden ref-counting concurrency semantics - #8583
Conversation
Motivation netty#8563 highlighted race conditions introduced by the prior optimistic update optimization in 83a19d5. These were known at the time but considered acceptable given the perf benefit in high contention scenarios. This PR proposes a modified approach which provides roughly half the gains but stronger concurrency semantics. Race conditions still exist but their scope is narrowed to much less likely cases (releases coinciding with retain overflow), and even in those cases certain guarantees are still assured. Once release() returns true, all subsequent release/retains are guaranteed to throw, and in particular deallocate will be called at most once. Modifications - Use even numbers internally (including -ve) for live refcounts - "Final" release changes to odd number (equivalent to refcount 0) - Retain still uses faster getAndAdd, release uses CAS loop - First CAS attempt uses non-volatile read - Thread.yield() after a failed CAS provides a net gain Result More (though not completely) robust concurrency semantics for ref counting; increased latency under high contention, but still roughly twice as fast as the original logic. Bench results to follow
|
Can one of the admins verify this patch? |
|
@netty-bot test this please |
|
Benchmark results: Pre- 83a19d5: Current (before): This PR (after): |
|
/cc @merlimat |
|
@njhill please also do the same for |
| int oldRef = refCntUpdater.getAndAdd(this, adjustIncrement); | ||
| if ((oldRef & 1) != 0) { | ||
| throw new IllegalReferenceCountException(0, increment); | ||
| } else if (oldRef <= 0 ? oldRef + adjustIncrement > 0 |
There was a problem hiding this comment.
nit: remove the else as you return in the previous if block
There was a problem hiding this comment.
Also please use {} to make it more readable and consistent with our code style.
| return true; | ||
| } | ||
| if (!firstTry) { | ||
| Thread.yield(); |
| return false; | ||
| } | ||
| if (!firstTry) { | ||
| Thread.yield(); |
| Thread.yield(); | ||
| } | ||
| } else if (decrement < realCnt) { | ||
| if (refCntUpdater.compareAndSet(this, rawCnt, rawCnt - decrement - decrement)) { |
There was a problem hiding this comment.
please add a comment why you subtract decrement twice.
|
@normanmaurer sure, sorry I missed your new test somehow. I was thinking to hold off on the Another thing which would probably be good to change - currently the count can actually go one further before "overflowing" ( Finally I did also benchmark your PR #8574 on the same system; let me know if you would like me to add those results, I omitted them above for brevity. |
|
@normanmaurer now updated with all the above |
|
@normanmaurer kind of a tangent but I also see it's possible to de-duplicate the common refcount logic, see 1ef2aa8. If you think this is of interest I can open a follow-on PR. |
Also match original Integer.MAX_VALUE overflow behaviour, other tidyup
2b0a80e to
7292f2f
Compare
| referenceCounted.retain(); | ||
| } | ||
|
|
||
| public static void main(String[] args) { |
There was a problem hiding this comment.
oops, fixed (checkstyle was same thing)
|
@netty-bot test this please |
|
@njhill de-duplicate as followup sounds good. |
|
@njhill also please fix the check style error: https://ci.netty.io/job/netty-centos6-java12-prb/189/console |
|
@netty-bot test this please |
|
@njhill @normanmaurer Thanks for looking into this! And nice idea on skipping the CAS on one leg! |
|
@netty-bot test this please |
1 similar comment
|
@netty-bot test this please |
|
@franz1981 PTAL as well |
|
@merlimat so does this fix your problem (I think it does but want to confirm) ? |
|
@normanmaurer It does indeed. Thanks! |
|
I would group all the uncommon paths into separate methods while leaving the common paths simple and clean: tomorrow I will take another look to the logic, nice work! |
|
Re "Thread.yield() after a failed CAS appears to provide a net gain": it is just an apparent gain (as seen in other context). It will trade latencies to get more throughput and I suppose the percentiles would show that. |
|
I think what we could do is factor out the less common code path into an extra method to ensure inlining can happen |
@normanmaurer told me that a retained slice/duplicate of an unpooled buffer does not have its own reference count, but then why don't we just implement
That'd be nice if addressed in this PR. |
|
I'm not super against the proposed change but I'm worried about:
|
|
@trustin I think we have two options here...
I would vote for 2) that said I can also life with 1). I mainly think 2) is fine as this code usually does not need to get touched very often so the complexity does not worry me as much . |
|
For sure it's better than reverting the optimization completely. :-) If we want correctness in the mentioned case, then (2) is the way to go. It'd still be nice if we could extract the slow path to a separate method. |
| throw new IllegalReferenceCountException(realCnt, -decrement); | ||
| } | ||
| rawCnt = refCntUpdater.get(this); | ||
| } |
There was a problem hiding this comment.
nit: consider simplify this:
for (boolean firstTry = true, int rawCnt = nonVolatileRawCnt();; firstTry = false, rawCnt = refCntUpdater.get(this)) {
if ((rawCnt & 1) != 0) {
throw new IllegalReferenceCountException(0, -decrement);
}
int realCnt = rawCnt >>> 1;
if (decrement == realCnt) {
// most likely case
if (refCntUpdater.compareAndSet(this, rawCnt, 1)) { // any odd number
deallocate();
return true;
}
} else if (decrement < realCnt) {
// all changes to the raw count are 2x the "real" change
if (refCntUpdater.compareAndSet(this, rawCnt, rawCnt - (decrement << 1))) {
return false;
}
} else if (!firstTry) {
throw new IllegalReferenceCountException(realCnt, -decrement);
}
if (!firstTry) {
// this benefits throughput under high contention
Thread.yield();
}
rawCnt = refCntUpdater.get(this);
}There was a problem hiding this comment.
This should also make the method size a bit smaller and so help with inlining.
There was a problem hiding this comment.
Same is true for AbstractByteBuf
There was a problem hiding this comment.
@normanmaurer lol I actually had the rawCnt = refCntUpdater.get(this) inside the for statement like that originally but thought better of it readability-wise (I have a bad habit of making things too compact), happy to do it though (I'm assuming you also meant to remove it inside the loop).
I don't think refCnt initialization can go in there though since the types have to match if there are multiple.
I didn't move out the Thread.yield() like that since it results in an additional check on one of the paths: when firstTry is true and decrement > realCount, which could happen in non-error cases especially since the first read is nonvolatile. But I guess probably uncommon enough to justify the simplification, I will do it.
I was also still planning to separate the less common paths although this will likely require some more duplication.
There was a problem hiding this comment.
@njhill I see... so yeah maybe just do the firstTry change + the split into methods. Thanks a lot for all your effort!
| int realCnt = rawCnt >>> 1; | ||
| if (decrement == realCnt) { | ||
| // most likely case | ||
| if (refCntUpdater.compareAndSet(this, rawCnt, 1)) { // any odd number |
There was a problem hiding this comment.
optional: this could just be getAndAdd(1) right?
There was a problem hiding this comment.
@carl-mastrangelo I think the compare is needed here since the count may have increased in which case we don't want the release to succeed (as soon as the ref changes to an odd number all other releases/retains will fail)
carl-mastrangelo
left a comment
There was a problem hiding this comment.
Code generally LGTM. One thing: I think the semantics of ref counting need to be better defined in Netty5, probably closer to what C++ programs do. I'll open an issue.
|
@normanmaurer @trustin @franz1981 I've had a go at decomposing the release logic to facilitate inlining of fast paths, PTAL |
|
@netty-bot test this please |
|
Changes seems fine 2 me: can you please do another round of benchmark with these changes? |
|
These "after" numbers look slightly too good to me relative to those ran before. I ran on the same system as the prior ones but maybe there was less other stuff going on, I will repeat the before ones too when I get a chance. |
|
Still LGTM. |
|
@njhill thanks a lot again! |
Motivation #8563 highlighted race conditions introduced by the prior optimistic update optimization in 83a19d5. These were known at the time but considered acceptable given the perf benefit in high contention scenarios. This PR proposes a modified approach which provides roughly half the gains but stronger concurrency semantics. Race conditions still exist but their scope is narrowed to much less likely cases (releases coinciding with retain overflow), and even in those cases certain guarantees are still assured. Once release() returns true, all subsequent release/retains are guaranteed to throw, and in particular deallocate will be called at most once. Modifications - Use even numbers internally (including -ve) for live refcounts - "Final" release changes to odd number (equivalent to refcount 0) - Retain still uses faster getAndAdd, release uses CAS loop - First CAS attempt uses non-volatile read - Thread.yield() after a failed CAS provides a net gain Result More (though not completely) robust concurrency semantics for ref counting; increased latency under high contention, but still roughly twice as fast as the original logic. Bench results to follow
Motivation AbstractReferenceCounted and AbstractReferenceCountedByteBuf contain duplicate logic for managing the volatile refcount in an optimized and consistent manner, which increased in complexity in netty#8583. It's possible to extract this into a common helper class now that all access is via an AtomicIntegerFieldUpdater. Modifications - Move duplicate logic into a shared ReferenceCountUpdater class - Incorporate some additional simplification for the most common single increment/decrement cases (fewer checks/operations) Result Less code duplication, better encapsulation of the "non-trivial" internal volatile refcount manipulation
Motivation AbstractReferenceCounted and AbstractReferenceCountedByteBuf contain duplicate logic for managing the volatile refcount in an optimized and consistent manner, which increased in complexity in #8583. It's possible to extract this into a common helper class now that all access is via an AtomicIntegerFieldUpdater. Modifications - Move duplicate logic into a shared ReferenceCountUpdater class - Incorporate some additional simplification for the most common single increment/decrement cases (fewer checks/operations) Result Less code duplication, better encapsulation of the "non-trivial" internal volatile refcount manipulation
Motivation AbstractReferenceCounted and AbstractReferenceCountedByteBuf contain duplicate logic for managing the volatile refcount in an optimized and consistent manner, which increased in complexity in #8583. It's possible to extract this into a common helper class now that all access is via an AtomicIntegerFieldUpdater. Modifications - Move duplicate logic into a shared ReferenceCountUpdater class - Incorporate some additional simplification for the most common single increment/decrement cases (fewer checks/operations) Result Less code duplication, better encapsulation of the "non-trivial" internal volatile refcount manipulation
Motivation
#8563 highlighted race conditions introduced by the prior optimistic update optimization in 83a19d5. These were known at the time but considered acceptable given the perf benefit in high contention scenarios.
This PR proposes a modified approach which provides roughly half the gains but stronger concurrency semantics. Race conditions still exist but their scope is narrowed to much less likely cases (releases
coinciding with retain overflow), and even in those cases certain guarantees are still assured. Once
release()returns true, all subsequent release/retains are guaranteed to throw, and in particulardeallocate()will be called at most once.Modifications
getAndAdd, release uses CAS loopThread.yield()after a failed CAS appears to provide a net gainAbstractReferenceCountedTestwritten by @normanmaurerResult
More (though not completely) robust concurrency semantics for ref counting; increased latency under high contention, but still roughly twice as fast as the original logic. Bench results to follow.
Fixes #8563